Gagan
Gagan

Reputation: 5656

Jquery get next sibling

I am facing some issues while getting elements of the sibling using jquery. I will try to explain.

The following is the HTML that i am currently working on ..

<p class="paraclass1" id="amazing1">
  <span class ="pascal1">
    <div class='pascal'>
        <INPUT id= "chk1" value="on" type="checkbox" />
    </div>
  </span>
</p>
<p>
  <label class='lblclass'>this is a label </>
</p>

what i would like to do is to navigate and find all the children that are present in the second p tag (right now only a label is present) . The following is the Jquery code that i am working on ..

$('#chk1').click(function(){
  alert($(this).parents('p#amazing1').next().children().length)

 // alert($('#chk1').parent().parent().attr('class'));
});

http://jsfiddle.net/gj1118/vWQxD/5/

Any help would be appreciated.

Thanks

Edit I am now trying to get the text of the label that is inside the second p tag element and its not working.... Is there something that I am missing .. ? I havent changed the fiddle yet , but since it was just a sample and since the tags were not being used, i let it remain like it for the sake of simplicity

Upvotes: 2

Views: 25515

Answers (1)

James Allardice
James Allardice

Reputation: 165971

Your jQuery should work fine. The problem in this case is your markup. The p element can only contain "phrasing content". The div element is not classed as phrasing content, so the browser will do its best to handle your markup by moving things around.

Chrome simply moves the p element to become the previous sibling of the div.

To fix the issue, you will need to change your markup. Your best bet may be to change the p element into another div. See an updated fiddle.


Side note. You may want to consider changing the .parents() call to a .closest() call. The .parents() method can return multiple elements if they match the selector. In this case that's not possible, but in the interest of maintainability, it could be a good change:

$(this).closest('#amazing1').next().children().length

Upvotes: 11

Related Questions