Set attributes in a single JS block

Asked

Viewed 55 times

0

Is there any way to do this? I’m repeating a lot of code with the setAttribute in a single element, so I’m researching if there’s any way to do this in a more organized and optimized way, but I haven’t found it yet.

Below is an EXAMPLE of what I’m doing and an EXAMPLE of what I wanted to do if possible:


Any link I will use in the example:

<a class="teste"></a>

JS code I am doing to set the attributes:

document.querySelector('.teste').setAttribute('href', 'https://www.teste.com')
document.querySelector('.teste').setAttribute('title', 'Site de Teste')
document.querySelector('.teste').setAttribute('id', 'idteste')

How I wanted if possible or something similar:

document.querySelector('.teste').setAttribute(['href', 'title', 'id'], ['https://www.teste.com', 'Site de Teste', 'idteste'])

Would have something similar to that already native to Javascript?

  • Natively has not.

2 answers

2


Could do using a function, passing as parameters the element, and attributes and values as arrays, and make a for in any of the arrays by setting the attributes:

function setAttr(el, atts, vals){
   for(var x=0; x<atts.length; x++){
      el.setAttribute(atts[x], vals[x]);
   }
   
   console.log(el);
}
setAttr(document.querySelector('.teste'), ['href', 'title', 'id'], ['https://www.teste.com', 'Site de Teste', 'idteste']);
<a class="teste">link</a>


Another way (even better) is to pass two parameters: the element and an object with pairs attribute:value for the function and make a for...in:

function setAttr(el, atts){
   for(var x in atts){
      el.setAttribute(x, atts[x]);
   }
   console.log(el);
}
setAttr(document.querySelector('.teste'), {'href': 'https://www.teste.com', 'title': 'Site de Teste', 'id': 'idteste'});
<a class="teste">link</a>

To be quite honest, I’d rather repeat it just like you are making. Using a function to apply attributes, in my opinion, is change 6 for half a dozen. I don’t see much advantage and I think it gets even worse from reading.

In this case, I would only assign the element to a variable not to repeat it several times:

var el = document.querySelector('.teste')
el.setAttribute('href', 'https://www.teste.com')
el.setAttribute('title', 'Site de Teste')
el.setAttribute('id', 'idteste')

0

You can simplify attributes this way:

document.getElementById("test").href = "http://www.cnn.com/";
document.getElementById("test").id= "novoID";
document.getElementById("test").required = false;
document.getElementById("test").disbled= false;

Instead of searching for ID you can use getElementByClass to search by class.

But I think you can’t change more than one attribute at a time using arrays, correct if I’m wrong.

  • 1

    This code will fetch the element test to the gift 4 which is precisely what the author is trying to avoid.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.