Languages
[Edit]
EN

JavaScript - iterate over all paragraphs on web page to get their text content

0 points
Created by:
chelsea
806

In this article, we would like to show you how to iterate over all paragraphs on web page to get their textContent using JavaScript.

Quick solution:

function getParagraphsText() {
    var paragraphs = document.querySelectorAll('p'); // finds all paragraphs
    var text = [];
    for (var i = 0; i < paragraphs.length; ++i) {
        text.push(paragraphs[i].textContent);
    }
    return text;
}

 

Practical example

In this example, we use querySelectorAll() method to get the collection of all paragraphs (p elements) on the web page. Then we iterate through the collection to get each paragraph textContent value and save it inside text variable.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <p>Paragraph 1</p>
  <p>Paragraph 2</p>
  <script>

    function getParagraphsText() {
        var paragraphs = document.querySelectorAll('p'); // finds all paragraphs
        var text = [];
        for (var i = 0; i < paragraphs.length; ++i) {
            text.push(paragraphs[i].textContent);
        }
        return text;
    }


    // Usage example:

    window.addEventListener('load', function() {
        console.log(getParagraphsText());
    });

  </script>
  <p>Paragraph 3</p>
  <p>Paragraph 4</p>
  </body>
</html>

Note:

The getParagraphsText() function needs to be executed after window load event or at the end of the script to make sure that all items are loaded before the function execution.

 

See also

  1. JavaScript - find all paragraphs on web page

References

  1. Document.querySelectorAll() - Web APIs | MDN
  2. Node.textContent - Web APIs | MDN

Alternative titles

  1. JavaScript - get text content from all paragraphs on web page
  2. JavaScript - how to get text from all paragraphs on particular web page?
  3. JavaScript - loop through all paragraphs on web page to get their textContent
  4. JavaScript - get textContent from all paragraphs on web page
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join