I have this markup:
<div class="click">click</div>
<div id="wrapper">
<div class="container">
<div data-attrfirst='type1'><span data-attrsecond='type2'>must be red</span></div>
</div>
</div>
I want to select all the .containers that:
1. are inside of #wrapper;
2. contain data-attrfirst='type1' element which, in its turn, contain data-attrsecond='type2' element.
My requirements:
1. My ‘#wrapper’, ‘type1’, ‘type2’ values MUST be kept as variables.
2. I MUST find this all inside of some tag (in this case, I choose body).
I tried this (asterisks may be removed, no difference):
<script>
$(document).ready(function () {
$('.click').click(function () {
var myid = '#wrapper';
var attrfirst = 'type1';
var attrsecond = 'type2';
var elem = $('*[data-attrfirst=' + attrfirst + ']').has('*[data-attrsecond=' + attrsecond + ']');
$('body').find(myid + ' .container').each(function (i) {
if ($(this).has('*[data-attrfirst=' + attrfirst + '] *[data-attrsecond=' + attrsecond + ']')) {
$(this).css('color', 'red')
}
});
$('body').find(myid + ' .container').each(function (i) {
if ($(this).has(elem)) {
$(this).css('color', 'red')
}
});
$('body').find(myid + ' .container').filter(function (i) {
return $('*[data-attrfirst=' + attrfirst + '] *[data-attrsecond=' + attrsecond + ']', this).length >= 1
}).css('color', 'red')
});
});
</script>
Where am I wrong? And I don’t understand from Jquery docs, does .has accept Jquery object?
Your question says that you want to find the
#container, so use this:Or, to be a little less confusing, you can work backwards:
However, from your code it seems that you actually want to find that last
data-attrsecond="type2"element. In that case, use this: