Flamur Beqiraj Flamur Beqiraj -4 years ago 84
CSS Question

jQuery not taking affect inside second child of ul

It is maybe wired, but I had a coupple of times problem with

:nth-child()
, this time on jQuery, I just can't select the second
ul
inside it the
li
and finally reach the
<a href="">
attribute!

To make it clear and simple, at the code below, I wanna remove the
href
attribute just to the second
ul
, not to the first one!
enter image description here

Here is the simple head:

<stle>
.cool {
color: red;
}
</style>

<script>
$(document).ready(function(){
$("ul:nth-child(2)>li>a").removeAttr("href");
});
</style>


The html code (Should not change anything here):

<h1>This is a heading</h1>
<ul class="cool">
<li class="aalsdlasd"><a href="http://www.google.com">Lol this row</a></li>
<li>Lol this row 2</li>
<ul class="cool" style="color: gold;">
<li>Lol this row</li>
<ul class="cool" style="color: grey;">
<li><a href="http://www.google.com">Lol this row Gold</a></li>
<li>Lol this row 2</li>
<li>Lol this row 3</li>
</ul>
<li>Lol this row 2</li>
<li>Lol this row 3</li>
</ul>
<li>Lol this row 3</li>
</ul>


And here the row that should change on the right way:

$("ul:nth-child(2)>li>a").removeAttr("href");


Find here the link to this problem jsfiddle.

Answer Source

Your issue is your selector. The first ul in your document matches :nth-child(2) because it is the second element in its parent.

If you want to match the ul inside of an li (i.e., a nested ul) you can do this instead:

$('li ul a').removeAttr('href')

By the way, your jsFiddle won't work as-is because you haven't declared jQuery as a dependency so $ is undefined.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download