0

What is the best way to get an element class by prefix?

For example I have:

<div class="cc-colour-red cc-size-big cc-width-narrow">

How to get those separately - the colour, te size and the width?

I hope that makes sense.

I have the DOM element selected. The final result would be "big", "red" and "narrow".

Thanks!

8
  • 3
    The best way would be to not use classes for this. Use individual data-* attributes for each property instead. Are you able to change the HTML format? Commented Jul 1, 2016 at 8:32
  • I know, but this is not possible in that particular case. Commented Jul 1, 2016 at 8:34
  • What do you want? The values of CSS color, font-size and width? Commented Jul 1, 2016 at 8:35
  • if i understood it correctly, please see my answer. Commented Jul 1, 2016 at 8:35
  • I want to get "big", "red" and "narrow" Commented Jul 1, 2016 at 8:36

5 Answers 5

2

Try this:

JavaScript

$("div").each(function(index, elem){
  var classes = $(elem).attr("class");
  var color = classes.replace(/.*cc-colour-([^\s]+).*/g, "$1");
  var size = classes.replace(/.*cc-size-([^\s]+).*/g, "$1");
  var width = classes.replace(/.*cc-width-([^\s]+).*/g, "$1");
  console.log(color, size, width); //red big narrow, blue small wide, green medium narrow
});

HTML

<div class="cc-colour-red cc-size-big cc-width-narrow">
<div class="cc-colour-blue cc-size-small cc-width-wide">
<div class="cc-colour-green cc-size-medium cc-width-narrow">
Sign up to request clarification or add additional context in comments.

Comments

2

If you want to get DOM element by class prefix, you can use this selector:

^=

If you are using multiple css classes, there is another selector for 'contains':

*=

Example:

$("[class^='cc-size-']")

4 Comments

This is half an answer at best. How do you get the key/values from the classes?
I should clarify. I have the DOM element selected, I want to get those values "big", "red" by prefixes "colour", "width" etc from element's classes.
Ok, got it. Look at @RoryMcCrossan answer, I think it's best one
Look at this question link I think that's exactly what you want
2

You can use document.querySelector(), with selector "[class|=cc]", .className, .replace() with RegExp /cc-|\s/g to exclude prefix from replacement string. You could alternatively use .match() to return an array of values

var values = document.querySelector("[class|=cc]")
             .className.replace(/cc-|\s/g," ");
console.log(values);
<div class="cc-colour-red cc-size-big cc-width-narrow">
</div>

Comments

2

The best way to achieve this would be to not use classes at all, and instead use individual data-* attributes for each property.

If you cannot change the HTML then you could achieve what you required by creating an array of objects which contains the key/value pairs. You can then use the index of the element to relate it to the key/value pairs object:

var arr = $('div').map(function() {
    var obj = {};
    for (var i = 0; i < this.classList.length; i++) {
        var className = this.classList[i];
        var matches = /^cc-(.+)-(.+)$/.exec(className);
        obj[matches[1]] = matches[2];
    }
    return obj;
}).get();

Example output:

[{
    "colour": "red",
    "size": "big",
    "width": "narrow"
}]

Working example

This approach has the benefit of being completely extensible; if you add any other classes then the code will automatically work without changes.

6 Comments

The div in OP does not have any id, won't that be a problem?
Nice workaround, but i'd strongly suggest using data values, too
@ToniMichelCaubet I agree, as I mentioned in the first paragraph. I can only assume that the OP is being provided the HTML from an external source, or is using this as a learning excercise.
@Arg0n possibly, although you could just as well use the elements index and put it in an array. I used an object in this case to make the example clearer, and association easier.
Well, the statement "If you cannot change the HTML ..." kindof contradicts the answer.
|
0

Use the following

$("div").prop("classList").forEach(function(entry) {
    console.log(entry.split('-')[2]);
});

2 Comments

the first description led to sth like this. now, in comments, he explained it in more detail.
Sorry, I should have clarified. I believe it makes more sense now in the first post.

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.