Given this HTML:
<ul>
<li><a href="/artists/gil_elvgren/activity_stream">Activity Stream</a></li>
<li><a href="/artists/gil_elvgren/likes">Likes</a></li>
<li>Favorites</li>
<li><a href="/artists/gil_elvgren/follows">Follows</a></li>
<li><a href="/artists/gil_elvgren/sketchbook_comments">Whiteboard</a></li>
</ul>
I want to inject the class="current"
into the single line item that does NOT have a link inside it.
How do I use jQuery to find an element that does NOT contain a child?
To specify the style for a list, use the list-style property to specify the type of marker. The selector in your CSS rule can either select the list item elements li , or it can select the parent list element ul so that its list elements inherit the style.
In CSS, to exclude a particular class, we can use the pseudo-class :not selector also known as negation pseudo-class or not selector. This selector is used to set the style to every element that is not the specified by given selector. Since it is used to prevent a specific items from list of selected items.
The element Selector The jQuery element selector selects elements based on the element name.
Use JQuery selector $('a[href*=part_of_link]'). it will select the element if any part of the attribute matches with value.
Select <li>
element that has no <a>
child using the :has
and :not
selector:
$("li:not(:has(a))").addClass("current");
jsFiddle
-- EDIT --
While this might be the shortest solution, readability aside, it definitely is not the best one in regards to speed.
With that in mind, I would suggest you check a great answer provided by @bazmegakapa.
Since this is something you (or anyone else including me) might end up using more than once, I have expanded jQuery a bit with this plugin/method you can use in order to DRY your code:
jQuery.fn.thatHasNo = function(element, method) {
if (typeof method === "undefined" || method === null) method = "children";
return this.not(function() {
return $(this)[method](element).length;
});
};
Which you can call with:
$("li").thatHasNo("a").addClass("current");
This extension will, by default (if second argument to method is not passed), check if there are any direct descendants (children) that match provided selector. However, you can provide any tree-traversal parameter as second argument to method. So, this can be written as either of the following:
$("li").thatHasNo("a", "children").addClass("current");
//...
$("li").thatHasNo("a", "find").addClass("current");
//...
$("li").thatHasNo(".class", "siblings").addClass("lame");
I have updated jsFiddle to reflect that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With