webkitfanz webkitfanz - 27 days ago 8
Javascript Question

Extract css and match with data-attribute

I have the following scenario:

<body class="theme-blue nav-black">
<a href="#" data-class="theme-blue">Blue theme </a>
<a href="#" data-class="nav-black">Dark Nav</a>
<a href="#" data-class="nav-white">Light Nav</a>
</body>


Trying to write a script to match the classes from and for each matching 'data-class' to add a class "active" to the element;

Whats the best way to go about doing this?

So the result should look like:

<body class="theme-blue nav-black">
<a href="#" data-class="theme-blue" class="active">Blue theme </a>
<a href="#" data-class="nav-black" class="active">Dark Nav</a>
<a href="#" data-class="nav-white">Light Nav</a>
</body>

Answer Source

Using jQuery

Get the classes from the body, split, map to an array of data attribute strings, and join. Add the class active to all selected elements:

var classNames = $('body')
  .attr("class")
  .split(' ')
  .map(function(c) {
    return '[data-class="' +  c + '"]';
  })
  .join(',');
  
$(classNames).addClass('active');

console.log(classNames);
.active {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body class="theme-blue nav-black">
  <a href="#" data-class="theme-blue">Blue theme </a>
  <a href="#" data-class="nav-black">Dark Nav</a>
  <a href="#" data-class="nav-white">Light Nav</a>
</body>

With jQuery:

Get the classList from the body, and convert it to a string query by casting the classList to an array using Array#slice, mapping the classes to data attributes strings, and joining with a comma. Then use Document#querySelectorAll to get the nodeList. Iterate the nodeList with NodeList#forEach, and add the active class to each node.

var classNames = [].slice.call(document.querySelector('body').classList, 0).map(function(c) {
  return '[data-class="' +  c + '"]';
}).join(',');

document.querySelectorAll(classNames).forEach(function(node) {
  node.classList.add('active');
});
.active {
  color: red;
}
<body class="theme-blue nav-black">
  <a href="#" data-class="theme-blue">Blue theme </a>
  <a href="#" data-class="nav-black">Dark Nav</a>
  <a href="#" data-class="nav-white">Light Nav</a>
</body>