Open In App

How to get text contents of all matched elements using jQuery ?

Last Updated : 05 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to get the text content of all matched class elements using jQuery. To get the text content, we use the text() method, which helps to set or return the text content of the element. 

Syntax:

$('Selector').text();

Approach 1: We create a div element that contains multiple div’s with class “content”, then we use the jQuery text() method on the “content” class, to get all text content of that particular class.

 

Example: In this example, we will display all contents of the matched class elements.

HTML




<!DOCTYPE>
<html>
  
<head>
    <title>
        How to get text contents of all
        matched elements using jQuery?
    </title>
  
    <script src=
    </script>
</head>
  
<body>
    <h1 style="color:green;">
        GeeksforGeeks
    </h1>
  
    <h3>
        How to get text contents of all
        <br>matched elements using jQuery?
    </h3>
  
    <div class="contents">
        <div class="content">Welcome</div>
        <div class="content">GeeksforGeeks</div>
        <div class="content">Web Development</div>
        <div class="content">HTML</div>
        <div class="content">CSS</div>
    </div>
  
    <script>
  
        // Select all elements content wit class "content"
        let cont = $('.content').text();
  
        // Display the text contents to the console
        console.log(cont);
    </script>
</body>
</html>


Output:

 

Approach 2: First, we will create a div element, that contains multiple div’s with the class “content” and then we use each() method on the “content” class to display the text content.

Example 2: In this example, we will display all contents of the matched class elements.

HTML




<!DOCTYPE>
<html>
  
<head>
    <title>
        How to get text contents of all
        matched elements using jQuery?
    </title>
  
    <script src=
    </script>
</head>
  
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
  
    <h3>
        How to get text contents of all
        <br>matched elements using jQuery?
    </h3>
  
    <div class="contents">
        <div class="content">Welcome</div>
        <div class="content">GeeksforGeeks</div>
        <div class="content">Web Development</div>
        <div class="content">HTML</div>
        <div class="content">CSS</div>
    </div>
  
    <script>
        let cont = $('.content');
  
        cont.each(function () {
            let textCont = $(this).text();
            console.log(textCont);
        });
    </script>
</body>
  
</html>


Output:

 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads