Jquery: Add rel attribute to <a> tags within all <li> tags of a certain class
Asked Answered
R

2

6

I'm trying to add a rel="lightframe" attribute to all my 'edit' links within my admin_links_node_edit class.

<li class="admin_links_node_edit">
<a href="[link]" title="Edit">Edit</a>
</li>

My code so far looks like this:

$('.admin_links_node_edit a').each(function() {
        $(this).attr('rel','lightframe'); 
});
Reservation answered 23/4, 2011 at 21:20 Comment(0)
G
17

You don't need to use each(). jQuery's selectors will do it for you :)

$('.admin_links_node_edit a').attr('rel', 'lightframe')

The above code will do the trick.

Galwegian answered 23/4, 2011 at 21:27 Comment(1)
Potentially buggy and vulnerable code. Do not do this. If you have links with other "rel" attributes it will be overwritten. If you loose "noopener" attribute - it jeopardizes your site for window.opener attack.Kirbee
A
1

If admin_links_node_edit is reused among other elements, you'll want to specify the element you're working on (li in this case). In addition, as Vijay Dev said, each() isn't needed, as attr() works on every element in the selector. Therefore:

$("li.admin_links_node_edit a").attr('rel','lightframe');
Allodial answered 23/4, 2011 at 21:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.