Home > Software design >  Alternative for document.getElelementById() for several IDs/elements
Alternative for document.getElelementById() for several IDs/elements

Time:10-09

I know that document.getElementById() won't work with several ids. So I tried this:

document.getElementsByClassName("circle");

But that also doesn't work at all. But if I use just the document.getElementById() it works with that one id. Here is my code:

let toggle = () => {
  let circle = document.getElementsByClassName("circle");
  let hidden = circle.getAttribute("hidden");

  if (hidden) {
    circle.removeAttribute("hidden");
  } else {
    circle.setAttribute("hidden", "hidden");
  }
}

CodePudding user response:

document.getElementsByClassName() returns a NodeList, and to convert it to an array of elements, use Array.from(). this will return an array containing all of the elements with the class name circle

Here is an example, which changes each element with the circle id:

const items = document.getElementsByClassName('circle')
const output = Array.from(items)

function change() {
  output.forEach(i => {
    var current = i.innerText.split(' ')
    current[1] = 'hate'
    current = current[0]   ' '   current[1]   ' '   current[2]
    i.innerText = current
  })
}
<p > I love cats! </p>
<p > I love dogs! </p>
<p >I love green!</p>
<p > I love waffles! </p>
<p > I love javascript! </p>
<p >I love tea!</p>
<button onclick="change()">Change</button>

CodePudding user response:

You can try this.

const selectedIds = document.querySelectorAll('#id1, #id12, #id3');

console.log(selectedIds);
//Will log [element#id1, element#id2, element#id3]

Then you can do something like this:

for(const element of selectedIds){
//Do something with element
//Example:
element.style.color = "red"
}
  • Related