skip to Main Content

I need to take the text "UNIT01". How I can do this using JQuery or JS?

`<div id="unit">
 <ul class="choices">
   <li>
    <div>UNIT01</div>
   </li>
   <li>
    <div>UNIT02</div>
   </li>
 </ul>
</div>`

2

Answers


  1. This code will access the text inside that div by accessing the div through its parent elements.

    var unit = document.getElementById("unit");
    var list = unit.getElementsByTagName("ul")[0];
    var items = list.getElementsByTagName("li")[0];
    var div = items.getElementsByTagName("div")[0];
    var text = div.innerHTML;
    alert(text);
    <div id="unit">
      <ul class="choices">
        <li>
          <div>UNIT01</div>
        </li>
        <li>
          <div>UNIT02</div>
        </li>
      </ul>
    </div>
    Login or Signup to reply.
  2. $( document ).ready(function() {
    var txt = $('.choices li:first-child>div').text()
    console.log( txt );});
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search