How to get p tag text in JavaScript | Get paragraph text example

How to get p tag text in JavaScript?

Use .innerHTML or .textContent to Get the text content of an element in JavaScript.

How to get p tag value in JavaScript Example code?

Let’s see the HTML examples and don’t forget the JavaScript methods are case sensitivity, so use it exactly the same.

innerHTML Example

The innerHTML property sets or returns the HTML content (inner HTML) of an element.

var text = document.getElementById("paragraphID").innerHTML;

Complete Example

<!DOCTYPE html>
<html>
<body>
    <p id="p1">Hello Text</p>
    <script>

       var text = document.getElementById("p1").innerHTML;

       alert(text);
   </script>

</body>
</html>

Output:

How to get p tag text in JavaScript

textContent Example

The textContent property sets or returns the text content of the specified node, and all its descendants.

var x =  document.getElementById("pTagId").textContent; 

Complete code

<!DOCTYPE html>
<html>
<body>
    <p id="p2">Another Text</p>
    <script>

        var x = document.getElementById("p2").textContent; 

       alert(text);
   </script>

</body>
</html>

Output:

How to get p tag value in JavaScript

Note: innerHTML method returns the HTML as its name indicates. Quite often, in order to retrieve or write text within an element, people use innerHTML. textContent method should be used instead. Because the text is not parsed as HTML, it’s likely to have better performance. Moreover, this avoids an XSS attack vector.

Do comment if you have any other example or doubts or suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.