Target multiple elements from the style of element

Viewed 81

Lets say i have multiple divs with the same class like

<div class="myDiv">1</div>
<div class="myDiv">2</div>
<div class="myDiv" style="display:none">3</div>
<div class="myDiv">4</div>

And here i want to target the div that has display:none which is the third div <div class="x" style="display:none">3</div>

I tried using this

const elements = document.querySelectorAll('.myDiv');
const element = elements.find(element => element.style.display == "none");
console.log(element)

but i got an error saying

elements.find is not a function

i tried to console.log the style of the elements to check the styles

const elements = document.querySelectorAll('.myDiv');
elements.forEach(element => console.log(element.style.display));

and it outputs this which is correct

""
""
"none"
""

But why doesn't the code that i tried work and why is elements.find not a function?

3 Answers

but i got an error saying

elements.find is not a function

That's because the NodeList returned by querySelectorAll isn't an array, it's a NodeList. You could create an array from it before doing the find:

const elements = document.querySelectorAll('.myDiv');
const element = [...elements].find(element => element.style.display == "none");
// −−−−−−−−−−−−−^^^^−−−−−−−−^
console.log(element);

That works because NodeList instances are iterable, so you can use spread notation to expand them into an array literal. (Other options are Array.from(elements), Array.prototype.slice.call(elements), or just using a for loop.)

You can also narrow your selector from .myDiv to .myDiv[style] so it only matches .myDiv elements that have a style attribute.

Ideally, though, if you can change things so that you don't have that inline style in the first place, I'd do that. For instance, if you use a class to hide the element:

<div class="myDiv">1</div>
<div class="myDiv">2</div>
<div class="myDiv hidden">3</div>
<div class="myDiv">4</div>

where hidden is defined as :

.hidden {
    display: none;
}

then you can ask the browser for the specific element you're interested in:

const element = document.querySelector(".myDiv.hidden");

Another way is to use Array.from

like so :

const elements = document.querySelectorAll('.myDiv');
const element = Array.from(elements).find(element => element.style.display == "none");
console.log(element)

Try that it's will diplay none the div number 3, any way you can use id as well to display none

  <div class="myDiv">1</div>
    <div class="myDiv">2</div>
    <div class="myDiv" style="display:none">3</div>
    <div class="myDiv">4</div>

JS***

let myDiv = document.getElementsByClassName("myDiv");
myDiv[2].style.display = "none";
Related