adamrooneydotnet
adamrooneydotnet

Reputation: 13

Set Multiple HTML Attributes Using Class Attributes in JavaScript

I've been able to achieve certain success with the following code to target id attributes using JavaScript to set multiple attributes:

function setAttributes(el, attrs) {
  for(var key in attrs) {
    el.setAttribute(key, attrs[key]);
  }
}
setAttributes(svgShape,{'d':complexShape,'fill':'#f04'});

However, would it be possible to use that code or a similar code to target class attributes, not id attributes?

Upvotes: 1

Views: 81

Answers (1)

Joe Thomas
Joe Thomas

Reputation: 6397

If you get the elements by their classname they come as an HTML element collection, therefore you must convert the class elements into an array and then iterate through them or use an Array call with a foreach:

Conversion to Array

function setAttributes(el, attrs) {
  var elements = [].slice.call(el);
  elements.forEach(function(element){
    for(var key in attrs) {
      element.setAttribute(key, attrs[key]);
  });
  }
}

Prototype Calling

function setAttributes(el, attrs) {
  [].forEach.call(el,function(element){
    for(var key in attrs) {
      element.setAttribute(key, attrs[key]);
    }
  });
}

Upvotes: 1

Related Questions