Home >Web Front-end >JS Tutorial >jQuery text manipulation: what are the commonly used methods?

jQuery text manipulation: what are the commonly used methods?

WBOY
WBOYOriginal
2024-02-29 08:18:031290browse

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.

1. Get the text content

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>

2. Set text content

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>");

3. Append content

In addition to setting text content, we can also append text to elements using .append()method.

Sample code:

$("#content").append(" Appended text");

4. Replace content

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>");

5. Clear the content

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn