Hello Readers,
Below is the difference between html() and text() methods in jquery:
Both .html() and .text() methods are used in jquery and both are jquery methods.
.html() is faster as compared to .text() method in jquery.
.html() method is only for html documents while .text() is used for both HTML as well as XML documents.
.text() method is most simple as compared to .html() method.
.html() method get the HTML content of the first element in the matched set while .text() method return all the string which display on browser or return the combines txt contents of all matched elements.
.text() method cannot be used on input elements.
For Example :
html() :-
<div id="testDiv">
<p>Cricket</p>
<p>Hockey</p>
<p>Football</p>
</div>
<input type="button" id="firstButton" name="submitButton" value="Submit"/>
<script type="text/javascript">
$(document).ready(function(){
$("#firstButton").click(function(){
var content=$("#testDiv").html();
alert(content);
});
});
</script>
<b>Output :</b>
<p>Cricket</p>
<p>Hockey</p>
<p>Football</p>
In the above code, it return the inner content of the div id textDiv inside a speific html element.
text():-
<div id="testDiv">
<p>Cricket</p>
<p>Hockey</p>
<p>Football</p>
</div>
<input type="button" id="firstButton" name="submitButton" value="Submit"/>
<script type="text/javascript">
$(document).ready(function(){
$("#firstButton").click(function(){
var content=$("#testDiv").text();
alert(content);
});
});
</script>
<b>Output :</b>
Cricket
Hockey
Football
In the above code, it gives the content of the div id textDiv and it can be used in XML as welll as HTML documents.
It will return the string inside the the html elements.
- Another Example of both the methods when pass the html documents inside the methods:
html():-
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").html("<p>Hello world</p>");
});
});
</script>
</head>
<body>
<button>Set text content for all p elements</button>
</body>
</html>
Output:
Hello world
text() :-
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").text("<p>Hello world</p>");
});
});
</script>
</head>
<body>
<button>Set text content for all p elements</button>
</body>
</html>
Output :
Hello world
0 Comment(s)