I know that getelelementbyid() won't work with several id's so I tried that : document.getElementsByClassName("circle"); but that also doesn't work at all but if I use just the getelementid it works with that one id. here 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:
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"
}
CodePudding user response:
document.getElementsByClassName returns a nodelist, and to convert it to an array of elements, use array.from(). this will return a js array containing all of the elements wit 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>