1

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?

2
  • Do you mean if the element has been fetched by ID vs by Class? Commented May 23, 2016 at 0:09
  • Hi @fatRaspberry if my answer has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. Commented May 28, 2016 at 4:01

1 Answer 1

1

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]);
    }
  });
}
Sign up to request clarification or add additional context in comments.

Comments

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.