jquery
  1. jquery-text

JQuery text()

The .text() method in JQuery is used to get or set the text content of an element.

Syntax

To get the text content of an element, you can use the following syntax:

$(selector).text();

To set the text content of an element, you can use the following syntax:

$(selector).text(content);

Use

The .text() method is useful when you want to get or set the text content of an element on a web page. You can use this method to manipulate the text content of HTML elements, such as headings, paragraphs, and lists.

Example

Here is an example of using the .text() method to get and set the text content of an HTML element:

<!DOCTYPE html>
<html>
<head>
    <title>JQuery text() Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <h1 id="title">This is a heading</h1>
    <p id="content">This is some text content</p>
    
    <script>
        // Get the text content of the h1 element
        var title = $('#title').text();
        console.log(title); // Outputs "This is a heading"
        
        // Set the text content of the p element
        $('#content').text('New text content');
    </script>
</body>
</html>
Try Playground

In this example, we use the .text() method to get the text content of the h1 element and set the text content of the p element. We use the console.log() method to output the text content of the h1 element to the browser console.

Summary

The .text() method in JQuery is a useful tool for manipulating the text content of HTML elements on a web page. It can be used to get or set the text content of an element and is especially useful when working with headings, paragraphs, and lists. Use it in your own projects to manipulate text content with ease!

Published on: