a selector which has this selector together with a class selector
Here is an analogy of my problem(a selector which has this selector together with a class selector):
Let say that I selects all yellow(classes) div e开发者_高级运维lements in a arbitrary HTML document. And I want each to check if the attribute is yes = 1. If the attribute 'yes' equals '1', then I want the child with class 'blue' have the attribute 'no' equals '1';
$('div .yellow').each(function(){
if($(this).attr('yes') == 1){
$(this '.blue:first-child').attr('no', 1);//This line needs to be fixed
}
});
I know that the line this.getElementsByClassName('blue')[0]
fixes this problem. But in my real problem (not this analogy) I want to use addClass and removeClass which only functions with jQuery objects. It is to cumbersome to use other functions than addClass and removeClass.
UPDATE:
Here is a code snippet from my real problem. I got some problem with "this" in javascript.
I want a invited button to have the className visible when I click on it. The button lies within a div element with className 'box'. I know that there are problem with 'this' on the code snippet. But I want the button and not the box to change to visible
$('.Box').each(function(){
if($(this).attr('hasButton') != 1){
var invite = document.createElement('div');
invite.className = 'invite invisible';
invite.innerHTML = 'invite';
$(this).attr('hasButton', 1);
this.appendChild(invite);
invite.addEventListener('mouseover', function(event){
$('.invite', this).removeClass('invisible');//this line is not functioning
$('.invite', this).addClass('visible');//neither this
}, false);
}
});
Ok solved it. I passed an element as attribute instead of classSelector.
$(invite).removeClass('invisible');
$(invite).addClass('visible');
Do you mean each blue div
lives in its own yellow div
? If so, try this:
$('.blue:first-child', this).attr('no', 1);
This tells jQuery to select .blue
elements only found within the scope of this
(which refers to the .yellow
element currently being iterated by each()
).
$('div .yellow[yes=1] .blue:first-child').attr('no', 1);
You can use the tagname[attrname=attrvalue]
to match arbitrary attributes.
You can also use find()
to only look within a specific element.
var yellow = $('div .yellow[yes=1]');
yellow.find('.blue:first-child').attr('no', 1);
精彩评论