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

早过忘川 提交于 2019-12-07 09:11:51

问题


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'); 
});

回答1:


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.




回答2:


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');


来源:https://stackoverflow.com/questions/5767025/jquery-add-rel-attribute-to-a-tags-within-all-li-tags-of-a-certain-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!