Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get paragraph text inside an element

People also ask

How do I get text within an element?

Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.

How do I get text inside a div?

Use the textContent property to get the text of a div element, e.g. const result = element. textContent . The textContent property will return the text content of the div and its descendants.

How do I get inner text in jQuery?

Answer: Use the jQuery text() method You can simply use the jQuery text() method to get all the text content inside an element. The text() method also return the text content of child elements.

How do you XPath a paragraph?

Type Relative XPath path //p[contains(@id,'1')] into the XPath field and click on 'Eval' button as shown below: 12. Observe that the paragraph text containing '1' text in the id attribute value of <p> tag of HTML source code got high lighted on the page as shown below: Please comment below to feedback or ask questions.


Alternatively, you can also pass the li element itself to your myfunction function as shown:

function myfunction(ctrl) {
  var TextInsideLi = ctrl.getElementsByTagName('p')[0].innerHTML;
}

and in your HTML, <li onclick="myfunction(this)">


Do you use jQuery? A good option would be

text = $('p').text();

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Where to JavaScript</title>
    <!-- JavaScript in head tag-->
    <script>
        function changeHtmlContent() {
            var content = document.getElementById('content').textContent;
            alert(content);
        }
    </script>
</head>
<body>
    <h4 id="content">Welcome to JavaScript!</h4>
    <button onclick="changeHtmlContent()">Change the content</button>
</body>

Here, we can get the text content of h4 by using:

document.getElementById('content').textContent

Try this:

<li onclick="myfunction(this)">

function myfunction(li) {
    var TextInsideLi = li.getElementsByTagName('p')[0].innerHTML;
}

Live demo


change your html to the following:

<ul>
    <li onclick="myfunction()">
        <span></span>
        <p id="myParagraph">This Text</p>
    </li>
</ul>

then you can get the content of your paragraph with the following function:

function getContent() {
    return document.getElementById("myParagraph").innerHTML;
}

HTML:

<ul>
  <li onclick="myfunction(this)">
    <span></span>
    <p>This Text</p>
  </li>
</ul>​

JavaScript:

function myfunction(foo) {
    var elem = foo.getElementsByTagName('p');
    var TextInsideLi = elem[0].innerHTML;
}​