Demo : https://www.lenlop123.com/2020/09/17-getset-text-html-val-attr-hoc-jquery_26.html
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<script src="https://code.jquery.com/jquery-3.6.1.min.js"
integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<input id="btn_gettext" type="button" value="get text">
<input id="btn_gethtml" type="button" value="get html">
<input id="btn_getval" type="button" value="get val">
<input id="btn_getattr" type="button" value="get attr">
<br><br>
<input id="btn_settext" type="button" value="set text">
<input id="btn_sethtml" type="button" value="set html">
<input id="btn_setval" type="button" value="set val">
<input id="btn_setattr" type="button" value="set attr">
<div id="div_1" style="background-color: violet;width: 250px;height: 100px;">Hello <b>Viet Nam</b> again</div>
<input id="txt_1" type="text" value="My name Hv" style="color: red" />
<script>
// get text
$("#btn_gettext").click(function () {
alert($("#div_1").text());
});
// get html
$("#btn_gethtml").click(function () {
alert($("#div_1").html());
});
// get val
$("#btn_getval").click(function () {
alert($("#txt_1").val());
});
// get attr
$("#btn_getattr").click(function () {
alert($("#txt_1").attr("style"));
});
// set text
$("#btn_settext").click(function () {
$("#div_1").text("-" + $("#div_1").text() + "1");
});
// set html
$("#btn_sethtml").click(function () {
$("#div_1").html("-" + $("#div_1").html() + "2");
});
// set val
$("#btn_setval").click(function () {
$("#txt_1").val("-" + $("#txt_1").val() + "1");
});
// set attr
$("#btn_setattr").click(function () {
$("#txt_1").attr("style", "color: blue");
});
</script>
0 Nhận xét