2

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");
  }
}
Michael M.
  • 10,486
  • 9
  • 18
  • 34
Theo
  • 21
  • 2

2 Answers2

2

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 class:

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 class="circle"> I love cats! </p>
<p class="circle"> I love dogs! </p>
<p class="square">I love green!</p>
<p class="circle"> I love waffles! </p>
<p class="circle"> I love javascript! </p>
<p class="square">I love tea!</p>
<button onclick="change()">Change</button>
  • thank you for the suggestion. I am very new to coding in general and I see that your method is properly working with your example but I can't implement it into my code, could you maybe explain to me how to do that, I tried but the implementation failed. I hope I am not asking fo too much :) – Theo Oct 06 '22 at 08:33
  • @Theo ```function toggle(){ let circle = Array.from(document.getElementsByClassName("circle")); let hidden = circle[0].hidden; circle.forEach(item => {item.hidden = !hidden}) }``` – Paxon Kymissis Oct 06 '22 at 22:07
  • Technically, `document.getElementsByClassName()` returns a [`HTMLCollection`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection), not a [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList). See [this StackOverflow answer](https://stackoverflow.com/a/15763707/13376511). – Michael M. Oct 09 '22 at 03:19
1

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"
}