开发者

Use jQuery to get a specific CSS class

开发者 https://www.devze.com 2023-02-22 01:34 出处:网络
I have an element with some CSS rules applied as follows: <span class=\"rule1 rule2 rule3[foo/bar]\"></span>

I have an element with some CSS rules applied as follows:

<span class="rule1 rule2 rule3[foo/bar]"></span>

I can use jQuery to retrieve the full class list using:

var classes = $("span").attr('css');

How do I select a specific rule, in this case rule3 complete with its array 开发者_运维问答contents?


You should not use a css class to store information. jQuery offers the feature to store all kinds of data into data-XXX propertys which in turn, are pulled into jQuerys .data() expando propertys.

In your example, this could look like

<span data-rules='{"rule1":"foo","rule2":"bar","rule3":"baz"}'></span>

This is a JSON-stringified version of your logic. By querying that node with jQuery like

var myspan = $('span');

you can now access this data attribute by calling

myspan.data('rules').rule3 // === "baz"

Reference: http://api.jquery.com/data/ (section: HTML 5 data- Attributes)


You could do..

var arr = $('span').attr('class').split(" ");

And then iterate over them as you wish.. arr[i]


I'd considering using the html5 data attribute instead.

Read up on http://html5doctor.com/html5-custom-data-attributes/


try this;

$('span[class~="rule1"]')

also you can try this one;

$('span.rule1')
0

精彩评论

暂无评论...
验证码 换一张
取 消