Boel
Boel

Reputation: 976

How to select the first text after a class in jQuery?

This is my HTML code:

<figcaption class="thumbcaption">
    New York City
    <div class="picture-attribution">
        <img class="avatar" width="16" height="16" alt="Edward Cunningham" src="http://images1.wikia.nocookie.net/__cb2/common/avatars/thumb/7/79/3392047.png/20px-3392047.png">
            Added by <a href="/wiki/User:Edward_Cunningham">Edward Cunningham</a>
    /div>
</figcaption>

I need to select the first text that appears after the thumbcaption class. In this case, the text would be:

New York City

If I do $(".thumbcation").text(), jQuery returns

New York CityAdded by Edward Cunningham

How can I select only the first text? I tried this:

var text = $(".thumbcation").not(".picture-attribution");
alert($(text).text());

but this doesn't work.

Thanks in advance!

Upvotes: 0

Views: 100

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

You need to get the text of the first text node

var text = $.trim($(".thumbcaption").get(0).firstChild.nodeValue);
//var text = $.trim($(".thumbcaption")[0].firstChild.nodeValue);

Demo: Fiddle

or

$.trim($(".thumbcaption").contents().first().text())

Demo: Fiddle

Upvotes: 3

Related Questions