Get paragraph text inside an element

user1544892 picture user1544892 · Jul 24, 2012 · Viewed 157.4k times · Source

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?

Answer

jay c. picture jay c. · Jul 24, 2012

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