Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector :first

Tags:

jquery

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/

like image 549
Jennifer Michelle Avatar asked Apr 20 '26 11:04

Jennifer Michelle


1 Answers

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.

like image 187
alex Avatar answered Apr 22 '26 02:04

alex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!