Nam Thai
Nam Thai

Reputation: 851

Element selector chaining in jquery

Here is what I'm trying to do: find the first div, find the first paragraph in that div, and get that element's text. The way I have done is so far is rather clumsy, with multiple $() wrapper around each element:

$($($('div')[0]).children('p').get(0)).text();

I wonder if there is a more elegant way to chain, something like:

$('div')[0]
  .children('p')[0]
  .text();
// That doesn't work

Upvotes: 0

Views: 2964

Answers (3)

Pranav C Balan
Pranav C Balan

Reputation: 115242

You can use :eq() for selecting using index

$('div:eq(0) p:eq(0)').text();

Also you can use :first , it's pseudo-class equivalent to :eq(0)

$('div:first p:first').text();

Upvotes: 2

PeterKA
PeterKA

Reputation: 24638

This should work just fine:

$('div').first().find('p').first().text();
//or to more closely match your code:
$('div').first().children('p').first().text();

What you were trying to write is:

$('div').eq(0).children('p').eq(0).text();
//Note: you're only selecting p elements that are direct children of the first div

NOTE: When you use [0] you reduce a jQuery collection to a DOM element and you lose all jQuery methods that you would run on a collection. Using .eq(0) or first() retains the jQuery methods as the result is still a jQuery collection.

Upvotes: 1

Lawrence Johnson
Lawrence Johnson

Reputation: 4043

All you need is this:

$('div:first-child p:first-child').text();

For your reference:

$('div')[0]
  .children('p')[0]
  .text();
// That doesn't work

The reason it doesn't work is because once you use the brackets to pull an element from the matching selectors provided by jQuery, you only get the base javascript DOM element (not a jquery object). Still, it's not a great way to navigate the DOM. If you really wanted to call them individually, it would go something like this (again, not recommended):

var __txtImLookingFor = '';
$.each($('div'), function() {
    if (__txtImLookingFor.length === 0) {
        $.each($(this).children('p'), function() {
            if (__txtImLookingFor.length === 0) {
                __txtImLookingFor = $(this).text();
            }
        });
    }
});

Obviously, navigating the DOM using the jQuery objects like that is really not a great approach unless you have a lot more conditional logic happening within.

Upvotes: 1

Related Questions