Can you pass in a class to the jQuery method parents()
?
I need to check for a menu item match to a data attribute and if there is change the color of a header/link.
How to find a parent with a known class in jQuery?
Relevant answer:
Pass a selector to the jQuery parents function:
d.parents('.a').attr('id')
http://api.jquery.com/parents/
The sample code from docs:
<script>
function showParents() {
$( "div" ).css( "border-color", "white" );
var len = $( "span.selected" )
.parents( "div" )
.css( "border", "2px red solid" )
.length;
$( "b" ).text( "Unique div parents: " + len );
}
$( "span" ).click(function() {
$( this ).toggleClass( "selected" );
showParents();
});
</script>
This led me to belive that you can pass in a class to that method but that I guess is not the case.
My code:
$(function() {
var tagName = $("#content").data("item")
$(".sub-menu a").each(function() {
var menuItem = $(this).text().toLowerCase();
if (menuItem == tagName) {
$(this).parents(".big-link").addClass("red");
}
});
})
.red {
color: red;
text-decoration: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content" data-item="most important"></div>
<div id="menu">
<a class="big-link" href="#">This Link should be RED</a>
<ul class="sub-menu">
<li>
<a href="#">Most Important</a>
</li>
<li>
<a href="#">Not Important</a>
</li>
<li>
<a href="#">Not Important</a>
</li>
<li>
<a href="#">Not Important</a>
</li>
</ul>
<a class="big-link" href="#">This Link should be untouched</a>
<ul class="sub-menu">
<li>
<a href="#">Not Important</a>
</li>
<li>
<a href="#">Not Important</a>
</li>
<li>
<a href="#">Not Important</a>
</li>
</ul>
</div>
The expectation is that the first link above the first list should be red, because the content of a menu item and the data attribute match.
In the same above attached answer it says to use .closest()
$(function() {
var tagName = $("#content").data("item")
$(".sub-menu a").each(function() {
var menuItem = $(this).text().toLowerCase();
if (menuItem == tagName) {
$(this).closest(".big-link").addClass("red");
}
});
})
.red {
color: red;
text-decoration: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="content" data-item="most important"></div>
<div id="menu">
<a class="big-link" href="#">This Link should be RED</a>
<ul class="sub-menu">
<li>
<a href="#">Most Important</a>
</li>
<li>
<a href="#">Not Important</a>
</li>
<li>
<a href="#">Not Important</a>
</li>
<li>
<a href="#">Not Important</a>
</li>
</ul>
<a class="big-link" href="#">This Link should be untouched</a>
<ul class="sub-menu">
<li>
<a href="#">Not Important</a>
</li>
<li>
<a href="#">Not Important</a>
</li>
<li>
<a href="#">Not Important</a>
</li>
</ul>
</div>
But that doesn't work either. Can you pass a class name into the .parents()
function? Or is there another function I should use for this?