-2

A string can contain attributes in the form like this:

let attr = ' min="0" step="5" max="100" '; 

or

let attr = ' min="2019-12-25T19:30" ';

etc.

Is there a function (either JS or jQuery) to assign these attributes to a HTML element?

Similar to setAttribute(name, value); but for multiple attributes.

8
  • Why can't you just call the function multiple times? if those are different attributes calling it multiple times should work, if they are the same attributes, just append the new value to old value and update it then. Commented Dec 7, 2021 at 10:47
  • let ele = document.getElementsByClassName("user-info")[0]; ele.min = "min"; console.log(ele.min); But your custom attrributes will not be visible in the tags, i guess. Commented Dec 7, 2021 at 10:49
  • 2
    Not unless you want to (re-)create the element's HTML code yourself in string form, and then let the browser parse it. It would probably make more sense to take your string value apart into name=value pairs first (via regular expression matching), and then loop over the result to use setAttribute with each one individually. Commented Dec 7, 2021 at 10:49
  • The element doesn't contain any attributes when it is created. Therefore there's no need to check if it exists or not. Commented Dec 7, 2021 at 10:51
  • Related: Setting multiple attributes for an element at once with JavaScript Commented Dec 7, 2021 at 10:51

2 Answers 2

1

There isn't any javascript method to do it, but you can convert your string to array and call setAttribute on the target element on every iterate of the array. like this:

let el = document.getElementById("targetId")  
let attrs = ' min="0" step="5" max="100" '.trim().replace(/\"/g,"").split(" ")
attrs.forEach(attr => {
  const [key,value] = attr.split('=');
  el.setAttribute(key,value)
})
Sign up to request clarification or add additional context in comments.

Comments

0

Please look at the answer at the following Setting multiple attributes for an element at once with JavaScript

Quoting from there, you can use the following helper function

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

And call it like so:

setAttributes(elem, {"src": "http://example.com/something.jpeg", "height": "100%", ...});

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.