1

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?

2
  • 2
    A class name with array contents? That kind of notation is new to me. Where do you have it from? And what do you mean by "select" - do you want to determine whether a specific link has this class? Commented Apr 4, 2011 at 9:36
  • Select as in grab rule3 and therefore be able to use the contents of the square brackets in a script. I've inherited the class rules & it's too late to change them all to use jQuery data() instead. Commented Apr 4, 2011 at 9:58

4 Answers 4

3

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)

Sign up to request clarification or add additional context in comments.

Comments

2

You could do..

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

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

1 Comment

But I agree with Peeter. Using jQuery's .data() would be a much more efficient practice.
0

I'd considering using the html5 data attribute instead.

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

Comments

0

try this;

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

also you can try this one;

$('span.rule1')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.