javascripthtmlparagraph

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?


Solution

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