Jose
Jose

Reputation: 11091

jQuery selector, syntax or bug?

This is weird I have markup like this

<div id='div1'>
  <ul id='ul1'>
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
  <div id='div2'>
    <ul id='ul2'>
      <li>4</li>
      <li>5</li>
      <li>6</li>
    </ul>
  </div>
</div>

in jquery I have a selector like this:

var el = $('#div2');
var liList = el.children('ul:first > li');

That should return the second set of li's but it returns the first set. But if I do this:

var el = $('#div2');
var liList = el.children('ul:first').children('li');

It returns the first set. Any ideas what's going on?

This made me take a double take because the 1st set of li's aren't even children of div2

I can obviously change my code to the latter, but is it a bug or am I just not writing my selector correctly?

UPDATE:
I was running jquery 1.4.1 and using jsfiddle like was suggested below showed different results with 1.4.2(the closest option to my config) and 1.4.4. So it seems like it was partly I wrote a wrong selector as indicated by Rocket and the jquery team fixed a bug that was in 1.4.1. :)

Gotta love StackOverflow :)

Upvotes: 0

Views: 255

Answers (2)

gen_Eric
gen_Eric

Reputation: 227200

.children() returns 'immediate children'. ul2 and its lis are children of div2, but ONLY ul2 is an 'immediate child'. To get all the lis, you need to use the second one.

The lis are 'immediate children' of their respective ul.

I hope this makes sence.

var el = $('#div2');
var ul2 = el.children('ul:first > li'); // retuns ul2, because it's an immediate child
                                       // the '> li' doesn't do anything
var liList = ul2.children('li');  // this will return all of ul2's lis

jsFiddle

Upvotes: 1

diagonalbatman
diagonalbatman

Reputation: 17992

Is it something to do with DIV2 being inside DIV1?

Upvotes: 0

Related Questions