I am trying to select text from a list. I want to select "First level text" but not "Second level text".
<div class="selectedText"></div>
<ul>
<li>First level text
<ul>
<li>Second level text</li>
</ul>
</li>
</ul>
My bad selector:
var firstLI = $('ul').find('li:first');
$('.selectedText').text(firstLI.text());
It pastes contents of the nested UL into my textbox.
How can I get only the LI text? Thanks.
Fiddle: http://jsfiddle.net/eYa3G/
Sounds like you just want the first text node of that element.
$("ul li:first").contents().first().text();
jsFiddle.
This gets the first node's text, which is a text node in your case.
Alternatively, if jQuery was in short supply...
document.querySelector("ul li:first-child").firstChild.data;
jsFiddle.
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