jQuery provides two methods to achieve this functionality - text() and html(). text() processes plain text; html() is similar to text(), except that it also supports HTML code.
//Set the content of the paragraph with ID "b5_a" as "This is a newly added text message";
$('#b5_a").text("This is a newly added text message");
//Add a paragraph to the div with the ID "b5_b" html code;
$("#b5_b").html("
Add a new html paragraph
");
Sometimes we have to read the page Content, this can also be achieved using text() and html(). Similarly, using text() will get plain text; using html() will get html code.
Copy code
The code is as follows: //Click the second button to view the text content of the related element$("button:eq(1 )").click(function(){
alert($('#b5_a').text());
});
//Click the fourth button to view the HTML content of the related element
$("button:eq(3)").click(function(){
alert($('#b5_a').html());
});
Note: The return value types of text() and html() are both string type (string). If we want to perform arithmetic operations on the return value, we can use the original JavaScript function: parseInt or parseFloat to convert the string first. Convert to integer or floating point type
Copy code
1.5
//Through the jQuery code below , you can sum the above list
$("button:eq(4)").click(function(){
var sum = 0;
$('li').each(function( index){
sum = parseFloat($(this).text());
});
alert(sum);
});