最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - select all html elements based on rel value - Stack Overflow

programmeradmin2浏览0评论

I have some html elements in my code like this

<div rel="test1">item1</div>
<div rel="test1">item2</div>
<div rel="test1">item3</div>
<div rel="test2">item4</div>
<div rel="test2">item5</div>

and I need a way to select all the divs that use rel="test1" and add a class to them how can I do this with jQuery?

I have some html elements in my code like this

<div rel="test1">item1</div>
<div rel="test1">item2</div>
<div rel="test1">item3</div>
<div rel="test2">item4</div>
<div rel="test2">item5</div>

and I need a way to select all the divs that use rel="test1" and add a class to them how can I do this with jQuery?

Share Improve this question edited Apr 25, 2012 at 17:13 gdoron 150k59 gold badges302 silver badges371 bronze badges asked Apr 25, 2012 at 16:56 themhzthemhz 8,42422 gold badges85 silver badges109 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6
$('div[rel=\'test1\']')

http://api.jquery./category/selectors/attribute-selectors/

You can then add a class with .addClass(). http://api.jquery./addClass/

​$('div[rel="test1"]')​.addClass("myClass");​

Demo

$('div[rel="test1"]').addClass('fooClass');

Live DEMO

$(function(){
    $("div[rel='test1']").addClass("newClass");       
});

working sample http://jsfiddle/4WEBk/13/

发布评论

评论列表(0)

  1. 暂无评论