Cover Image for jQuery text() method
148 views

jQuery text() method

The .text() method in jQuery is used to get the combined text content of an element or set the text content of an element. It’s a versatile method for working with the text within HTML elements.

Getting Text Content:

To retrieve the text content of an element, you can use the .text() method without any arguments. Here’s an example:

<p>This is some text.</p>
var textContent = $("p").text();
console.log(textContent); // Outputs: "This is some text."

In this example, we select the <p> element and use the .text() method to get its text content, which is “This is some text.”

Setting Text Content:

You can also use the .text() method to set the text content of an element. Here’s an example:

<p id="myParagraph">This is an empty paragraph.</p>
$("#myParagraph").text("Now it has some text.");

In this example, we select the paragraph with the ID “myParagraph” and set its text content to “Now it has some text.” The paragraph’s original content is replaced with the new text.

Callback Function:

The .text() method also allows you to use a callback function that calculates the new text content based on the existing content. For example:

<p id="myParagraph">This is some text.</p>
$("#myParagraph").text(function(index, text) {
  return "New text: " + text;
});

In this case, the callback function receives the current index and the current text content as arguments. The function returns the new text content, which is then set for the element.

The .text() method is particularly useful for updating the text content of elements, such as updating labels, changing displayed messages, or modifying textual content dynamically in your web application.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS