44

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?

10 Answers10

55

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)">

jay c.
  • 1,521
  • 10
  • 9
16

Do you use jQuery? A good option would be

text = $('p').text();
casraf
  • 21,085
  • 9
  • 56
  • 91
13
<!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
Ivan
  • 34,531
  • 8
  • 55
  • 100
ankit keshari
  • 139
  • 1
  • 4
7

Try this:

<li onclick="myfunction(this)">

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

Live demo

Engineer
  • 47,849
  • 12
  • 88
  • 91
6

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;
}
Tom
  • 4,096
  • 2
  • 24
  • 38
1

Use jQuery:

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

should work.

Stefan van den Akker
  • 6,661
  • 7
  • 48
  • 63
Rocky Pulley
  • 22,531
  • 20
  • 68
  • 106