开发者

jquery .children() of .get()

Example:

<ul>
  <li>
    <a></a>
  </li>
  <li>
    <a></a>
  </li>
</ul>

I can use $('ul').children('li').get(0); to get the list item. How can I use .children('a') to traverse down the tree?

I tried something like $('ul').children('li').get(0).children('a'); but that does not work.


For future reference:

  1. I will be doing other things to the li other than traversing down to the a, which is why I am trying to use .children()开发者_开发问答.
  2. Index will be dynamic and not always 0.

Which is why .eq() is the preferred answer. Now I can do something like:

_load = function(index) {
  image_get = thumbs.children('li').eq(index);

  [...]

  $(function() {
    var img = $(new Image());
    img
      .load(function() {
        [...]
      }
      .attr('src', image_get.children('a').attr('href'));
  });
}

_load(0);

^^^ WIP. Code unfinished.


.get() returns a DOM Element. You can wrap it back in a jQuery object like:

$($('ul').children('li').get(0)).children('a');

But I think what you really want is .eq() instead of .get():

$('ul').children('li').eq(0).children('a');

Edit

As Reid kindly pointed out in the comment below,

$('ul').children('li').eq(0).children('a');

is semantically equivalent to the more concise :

$('ul > li:first-child > a');

which does the same as the above with a single selector.


Why not just put it all in the selector and let that do all the work for you:

$('ul li:first a')

This will get a jQuery object for the first <a> tag in your sample HTML.

The selector logic works like this: Find all ul tags, the find the first li tag in each, then get all the a tags in each of the first li tags. The result is a jQuery selection which you can then apply various operations to.

Demo here: http://jsfiddle.net/jfriend00/5qZP5/


You can do this

$('ul li a:first');

http://jsfiddle.net/jasongennaro/yCAT6/

$('ul li a'); returns all of the as in that list.

:first filters for just the first.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜