Method html
The html
method allows you to change the text of an element and get it along with tags.
Syntax
Getting text:
$(selector).html();
Change text:
$(selector).html(new text);
Additionally
The html
method can apply a given function to each element in the set. The first parameter of the function is the number of the element in the set, and the second parameter is the current text of the element:
$(selector).html(function(number in set, current element text));
The variable names in the function can be any. For example, if we give the first parameter the name index
- then inside our function the variable index
will be available, which will contain the number in the set for the element that the function is currently processing. Similarly, if we give the second parameter, for example, the name value
- then inside our function the variable value
will be available, which will contain the text of the element that the function is currently processing:
$(selector).html(function(index, value) {
// variables index and value are available here
});
The text of each element will change to the one that the function returns specifically for that element.
Example
Let's display the contents of our paragraph:
<p id="test">text</p>
let text = $('#test').html();
alert(text);
Example
Let's change the content of our paragraph:
<p id="test">text1</p>
$('#test').html('text2');
HTML the code will look like this:
<p id="test">text2</p>
Example
Let's change the content of our paragraph to text with tags:
<p id="test">text1</p>
$('#test').html('<span>text2</span>');
HTML the code will look like this:
<p id="test"><span>text2</span></p>
Example
Let's add a serial number in the set to the end of each paragraph:
<p>text</p>
<p>text</p>
<p>text</p>
$('p').html(function(index, value){
return value + ' ' + index;
});
HTML the code will look like this:
<p>text 1</p>
<p>text 2</p>
<p>text 3</p>