Finding Nested value(s) within nested values in jQuery
I have the following code with the intention of locating values from within a targ开发者_JAVA百科eted div as follows:
$('#combineDiv').children().each(function(){
if ($(this + ":first-child").attr('class') == 'combinedColumn') {
alert('found ONE!');
}
});
I have a hidden input in some of the divs within the children of the div '#combineDiv'... but, I dont know how to combine the 'THIS' keyword with the appropriate selector... :(
remember this
is going to return an object from the DOM, so $(this + ":first-child")
probably isn't going to give you what you want (it'll probably return something like [object Object]:first-child.
Instead try accessing the ID, or whatever it is you're after, off of that this
object
$(this.ID + ":first-child").attr('class')
$(this).filter(":first-child")
Not sure what you're trying to do, but my assumption is that you want to look inside each child of the #combineDiv
for a :first-child
, that is a .combinedColumn
$("#combineDiv > * > .combinedColumn:first-child");
Use .filter("selectors")
,i.e. $(this).filter(":first-child")....
In fact you could use $(this).filter(":first-child .combinedColumn")
I believe.
use .find to travel more than one level down
$('#combineDiv').find(selector).each(
function(){
if ($(this + ":first-child").attr('class') == 'combinedColumn') {
alert('found ONE!');
}
});
You can use the has
method to get the elements that has children that matches a selector, intead of looping through the children yourself:
$('#combineDiv').children().has('.combinedColumn:first-child').each(function(){
alert('found ONE!');
});
Example:
With this HTML:
<div id ="combineDiv">
<div><span class="none">1</span><span class="none">1</span></div>
<div><span class="none">2</span><span class="combinedColumn">2</span></div>
<div><span class="combinedColumn">3</span><span class="none">3</span></div>
<div><span class="combinedColumn">4</span><span class="combinedColumn">4</span></div>
</div>
This will match the third and fourth child div and make their background gray, as they have a first child with the class "combinedColumn":
$('#combineDiv').children().has('.combinedColumn:first-child').css('background', '#ccc');
精彩评论