Jade
Jade

Reputation: 153

Adding attribute to Link via jQuery

I have the following HTML:

<div class="navv">
<ul>
<li><a href="#">HOME</a></li>
<li class="dropdown"><a href="#">MAPPING</a></li>
</ul>
</div>

What I want is to loop through each "li" and then add an attribute to that particular Link "a href" inside the "li" which has the class "dropdown"

I have managed to work it out till:

The only part left is that I cannot manage to add a new attribute to the 'a href' for that particular 'li' that has the class 'dropdown'

This is what I have tried so far:

<script type="text/javascript">
$(document).ready(function(){
    $(".navv ul li").each(function(index){
        if($(this).hasClass('dropdown')){
         // Adding a new attribute to the link tag  
         // referring to the particular "li" and "a" inside it and adding attribute, but this doesen't work.
         $(this).("a").attr('data-toggle','dropdown');    
        }
    })
});
</script>

Upvotes: 0

Views: 4960

Answers (3)

user2826254
user2826254

Reputation: 116

Try this

$(this).children("a").attr('data-toggle','dropdown');    

Upvotes: 1

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

You code too much! Try this :

$("li.dropdown a").attr('data-toggle', 'dropdown');

Also, except if you really need the attribute on the DOM node (because you are selecting it with bracket [] selector), use .data():

$("li.dropdown a").data('toggle', 'dropdown');

Upvotes: 3

Try

you are attr to li tag you need to find a in li

$(this).find("a").attr('data-toggle','dropdown');    


Better use

$("li.dropdown a").data('toggle', 'dropdown');

.data()

Upvotes: 0

Related Questions