Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting text values of li (without text in nested items)

<ul>
  <li class="item-i">AI</li>
  <li class="item-ii">AII
    <ul class="level-2">
      <li class="item-a">A</li>
      <li class="item-b">B</li>
      <li class="item-c">C</li>
    </ul>
  </li>
  <li class="item-iii">III</li>
</ul>

How can I get values AI AII A B C III?

What I tried so far is following:

$(document).ready(function() {
    $('li').each(function(index) {
     alert($(this).text());
    });
});

But it does not gave me required results. When it reaches "item-ii" it gave all result.

I want item one by one.

like image 699
Tahir Avatar asked Oct 25 '22 22:10

Tahir


1 Answers

$(function(){
  var text = $('li').map(function(){
    return $(this).contents().map(function(){
      return this.nodeType==3 ? this.nodeValue : "";
    }).get().join('');
  }).get().join(' ');
  console.log(text);
  // AI AII
  //
  //     A B C III
});

The contents() method gives you both text nodes and child nodes. Text nodes have a nodeType of 3. For less "functional"-style code, try this:

$(function(){
  $('li').each(function(){
    $(this).contents().each(function(){
      if (this.nodeType==3){
        console.log(this.nodeValue.replace(/^\s+|\s+$/g,''));
      }
    });
  });
  // AI
  // AII
  // 
  // A
  // B
  // C
  // III
});

Note that there is still a blank text node due to the markup.

like image 196
Phrogz Avatar answered Dec 04 '22 10:12

Phrogz