I would like to know the difference between two methods or functionalities of jQuery that can be confusing in my case, even reading the API of both utilities such as:
- .text ()
- .html ()
According to w3s, .text () places and retouches a value in an attribute or label of our HTML; and html () places and returns a value in an attribute or tag with the possible difference of adding html code.
Example .text ():
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").text("Hello world!");
});
});
</script>
</head>
<body>
<button>Set text content for all p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
Example .html ():
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").html("Hello <b>world!</b>");
});
});
</script>
</head>
<body>
<button>Change content of all p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
Why is the difference really? Can you use both indistinctly?