[javascript] Get paragraph text inside an element

I want to have the text value from a <p> inside a <li> element.

html:

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

javascript:

function myfunction() {
  var TextInsideLi = [the result of this has to be the text inside the paragraph"];
}

How to do this?

This question is related to javascript html paragraph

The answer is


If you use eg. "id" you can do it this way:

_x000D_
_x000D_
   (function() {_x000D_
    let x = document.getElementById("idName");_x000D_
    let y = document.getElementById("liName");_x000D_
    _x000D_
    y.addEventListener('click', function(e) {_x000D_
        y.appendChild(x);_x000D_
    });_x000D_
_x000D_
  _x000D_
})();
_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
    <title></title>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <p id="idName">TEXT</p>_x000D_
    <ul>_x000D_
        <li id="liName">_x000D_
_x000D_
        </li>_x000D_
    </ul>_x000D_
</body>_x000D_
<script src="js/scripts/script.js"></script>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_


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;
}?

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;
}

Try this:

<li onclick="myfunction(this)">

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

Live demo


Do you use jQuery? A good option would be

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

Add an Id property into the P tag with value like text or something:

function gettext() {
    var amount = document.getElementById('text').value;
}

Use jQuery:

$("li").find("p").html()

should work.


<!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