<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.
$(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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With