JQuery Little Help Needed!

Hello, OK I have this code. Now I want a red background added in Item 3 and Item 4 only (not in its children). But its not working. What I am doing wrong?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Navigation</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>

<style>
.bg {
	background: red;
}
</style>

<script>
$(document).ready (function () {
	$("div ul li").has("ul").parent("li").addClass("bg");
});
</script>

</head>
<body>

<div>
<ul>
<li><a href="#">Item 1</a></li>
<li><a href="#">Item 2</a></li>
<li><a href="#">Item 3</a>
	<ul>
	<li><a href="#">Item 3.1</a></li>
	<li><a href="#">Item 3.2</a></li>
	<li><a href="#">Item 3.3</a></li>
	</ul>
</li>
<li><a href="#">Item 4</a>
	<ul>
	<li><a href="#">Item 4.1</a></li>
	<li><a href="#">Item 4.2</a></li>
	<li><a href="#">Item 4.3</a></li>
	</ul>
</li>
</ul>
</div>

</body>
</html>

Edit: I shouldn’t have used the parent(“li”). But then how to achieve what I want ?

add the class to the <a>, not the <li>.

$("div ul li").has("ul").parent("li a").addClass("bg");

didn’t worked.

obviously. this is not a working filter expression for parent(). <a> is not even a parent of <ul>.

How about:

$("div ul li").has("ul").addClass("bg");

Then use css:

.bg > a {
	background: red;
}

Or with no js use css only:

ul li a:first-child:nth-last-child(2){background:red}

IE9+ only (and all other modern browsers),

1 Like

Thank you Dormilich.

Thank you Paul. Your solution worked. So bad it didn’t came in my mind.

Thank you to both of you.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.