I want to add a handler that will change the background of some elements with a class of controlButtonInline
when the great-grandparent of an element with a title
that begins with Name
is clicked.
So far I have this but the event never runs. I don't think that ABC
is getting populated with an id that the second jQuery can recognise.
var ABC = $('select[title^="Name"]')
$(ABC).parent().parent().parent().click(function() {
$('.controlButtonInline').css({
'background': 'black'
});
});
Any help gratefully received!
------EDIT 1------
I still can't get this to work, here is more information if anyone doesn't mind looking. I want to enact the click handler by clicking on the top DIV (I've written id="unstableID" because in the program that I'm using that ID will constantly change) but I need to identify this element from the title of the descendent DIV.
var ABC = $('select[title^="Name"]')
ABC.parent().parent().parent().click(function() {
$('.controlButtonInline').css({
'background': 'black'
});
});
controlButtonInline {
width: 10px;
height: 10px;
background: red
}
<DIV id="unstableID">
<DIV>
<DIV>
<DIV title="Name is BI">
</DIV>
</DIV>
</DIV>
</DIV>
<DIV class="controlButtonInline">Text
</DIV>
The problem is because the element with the title
attribute is a div
, not a select
. Fix the jQuery selector and the code works.
That being said, it's better practice to use addClass()
over css()
as it doesn't place an CSS logic in your JS file. Also note that you should avoid using chained parent()
calls where possible. closest()
is much better practice:
var $ABC = $('div[title^="Name"]')
$ABC.closest('.great-grandparent').click(function() {
$('.controlButtonInline').addClass('foo');
});
.controlButtonInline {
width: 10px;
height: 10px;
background-color: red
}
.controlButtonInline.foo {
background-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="unstableID" class="great-grandparent">
<div>
<div>
<div title="Name is BI">Click me</div>
</div>
</div>
</div>
<div class="controlButtonInline">Text</div>