jquery: select first child node
lets say i have a tree of the following structure:
<div>node level1
<div>node level2
<div>node level3...etc
Is there a way in jQuery, that if div level1开发者_Go百科 is clicked, only divs of level2 respond?
meaning:
$('div').click(function(){
$('div').children(first div child).css('color','red');
})
thanks for any input!
::EDIT::
hey everyone, thanks for your patience and input. i stubbornly went about solving this problem, and it worked out. i just had to find a way to crack inside the structure of my tree and it all became very clear. i basically wanted to find a way to make a superfish-esque tree collapse/expand without being stuck inside the "li ul li" examples i had been seeing as I felt they were a bit opaque. this fiddle has my solution. note: i am assuming that if something has 0 children it will most likely be a link to be followed. i am sure with the structure I have set out, and your able minds will be able to solve this last step.thanks for all help and i look forward to any feedback.
final note: this can be easily soft coded to agree with any tree structure size. a while loop that acknowledges children or node clicked, that allows for concatenation and calls an eval function will be able to drill all the way down in the sub-nodes and make sure they are all hidden before the main node is also hidden.just a side thought.
You can do it like this:
$('div').click(function(){
$(this).children('div').css('color','red');
});
Instead of selecting all <div>
elements again, use this
and do .children()
from there to get the immediate child <div>
elements. Here's a quick example, note for this example, the <div>
s need a color
initially, otherwise it'll cascade down...even though it wasn't actually applied to the level 3 elements.
This is probably what you're looking for:
http://api.jquery.com/first-child-selector/
It's the matter of the css selector as jquery use it.
I think you could simply define a class to the div you want to select:
<div class="Level1">node level1
<div class="Level2">node level2</div>
</div>
Then select it in jquery like this:
$('div.Level1').click(function(){
$(this).children('div.Level2').css('color','red');
})
Edited for .click()
context:
Inside the click event you'll have the this
jQuery object to work with (which is the element which has been clicked. So you can use the .children()
to access all of the children elements (it will only return immediate children, so just items level-2 items in your scenario):
$('div').click(function(){
$(this).children().css('color','red');
}
Or, if you only want the first level-2 item you could use the :first-child
selector:
$('div').click(function(){
$(':first-child', this).css('color','red');
}
精彩评论