Home > Article > Web Front-end > jQuery text manipulation: what are the commonly used methods?
jQuery is a very popular JavaScript library used to simplify DOM manipulation in web development. During the development process, text content often needs to be manipulated, including operations such as obtaining, setting, and replacing. This article will introduce some commonly used jQuery methods for manipulating text and provide specific code examples.
You can easily get the text content of the element using jQuery. Commonly used methods are .text()
and .html()
. .text()
Returns the plain text content of the element, excluding HTML tags; .html()
Returns the HTML content of the element.
Sample code:
<div id="content"> <p>This is a text content.</p> </div>
var textContent = $("#content").text(); console.log(textContent); // 输出:This is a text content. var htmlContent = $("#content").html(); console.log(htmlContent); // 输出:<p>This is a text content.</p>
Similarly, you can also use jQuery to easily set the text content of an element. You can use .text()
and .html()
methods.
Sample code:
$("#content").text("New text content"); $("#content").html("<p>New HTML content</p>");
In addition to setting text content, we can also append text to elements using .append()
method.
Sample code:
$("#content").append(" Appended text");
When you need to replace the text content of an element, you can use the .replaceWith()
method.
Sample code:
$("#content").replaceWith("<div>New element content</div>");
If you need to clear the content of the element, you can use the .empty()
method.
Sample code:
$("#content").empty();
Through the above code examples, we can see that jQuery provides a wealth of methods to manipulate text content, making web development more convenient and efficient. Hope this article helps you!
The above is the detailed content of jQuery text manipulation: what are the commonly used methods?. For more information, please follow other related articles on the PHP Chinese website!