Meek
Meek

Reputation: 3362

Select class that starts with a prefix and store full class name as variable

I need to find a class based on what the class name starts with, and then add the full class name to another element.

<div class="slide theme-light-blue">Test</div>
<div class="result"></div>
var theme = $('[class^="theme-"]').filter(function() {
    return this.className.match(/(?:^|\s)theme-/);
});
$(".result").addClass(theme);

I think I got the first part by using regex to find all classes starting with "theme-", but I don't know how to store the full class name as a variable that can be added to another element. In this example I'm expecting the class "theme-light-blue" to be added to the .results div. The code I have here is not working. See fiddle here.

Upvotes: 2

Views: 1269

Answers (2)

A.B
A.B

Reputation: 20445

if you have second class in every case then you can use attribute getter( attr() ) to get class of your selection and split it with split()

var theme = $('[class^="theme-"]').attr('class')[0].split(' ')
         .filter(function(a){return a.match(/(?:^|\s)theme-/)
          })[0];
$(".result").addClass(theme);

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337691

Firstly you should use the 'Attribute contains' selector to find elements which have a theme-* class, as it may not necessarily be the first class applied to the element. Your use of filter() is also incorrect as it's used to reduce a matched set of elements based on a supplied filter, and it returns a jQuery object, not a string.

To achieve what you require you can loop through the classList property of each .theme-* element and apply that class to the next .result element in the page. Try this:

$('[class*="theme-"]').each(function() {
    for (var i = 0; i < this.classList.length; i++) {
        if (this.classList[i].indexOf('theme-') == 0)
            $(this).next('.result').addClass(this.classList[i]);
    }    
});

Updated example

This is obviously assuming that only one theme-* class is applied to an element.

Upvotes: 2

Related Questions