0

I am trying to use isotope in connection with a CuteNews system, and to get the filtering to work I need to print some identifiers in my class declaration of each isotope-item. Link to Isotope

In CuteNews my news items can have multiple categories assigned to them, so when I load them up in my HTML they could belong to e.g. "Domestic" and "Food" at the same time, which could be e.g. category no. 1 and 5. In CuteNews the only way I can get the category extracted and tossed into my HTML is to use a function that prints all categories as a string, that reads "1,2,5,21" if the categories are 1, 2, 5 and 21. Now that is no good if I need to add it as a class in isotope, as this would produce

<div class="isotope-item 1,2,5,21">...content...</div>

So I need some way of transforming the above (which is what ends up in my HTML right now) into

<div class="isotope-item cat1 cat2 cat5 cat21">...content...</div>

This way I could apply the isotope filtering on e.g. all classes with cat1 and so on.

As I see it I need to strip away the commas, which could be done easily using some JS like this jQuery find and replace string. But I don't want to replace all commas on my entire page!

How can I target only what is inside the class="isotope-item" DIV and put a "cat" in front of each number and then replace the comma with a space?

Community
  • 1
  • 1

1 Answers1

1

You can do a replace like

var els = document.getElementsByClassName('isotope-item'),
    el, array;
for (var i = 0; i < els.length; i++) {
    el = els[i];
    el.className = el.className.replace(/(\d+)(,|$|\s)/g, function (all, value) {
        return 'cat' + value + ' '
    })
}

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531