Home > front end >  How to select an element with specific css value in javascript
How to select an element with specific css value in javascript

Time:05-01

I want to select an element if it has a css as display block then do this function. If the element has the css as display block then remove ('hide') class from the header class.. This is what I want to do.. Any help?

CodePudding user response:

Well, there are two solutions depending on what you want:

Solution 1

Looping through all elements and removing hide class from the current element if it has display block value in its style.

var elements = document.getElementsByTagName("*");

for(let i = 0; i < elements.length; i  ) {
    if(elements[i].style.display == "block") {
        elements[i].classList.remove("hide");
    }
}

Solution 2

Getting the reference of the element via HTML id.

var element = document.getElementById("YourElementID");

if(element.style.display == "block") {
    element.classList.remove("hide");
}

You can define an id like this in your HTML file:

 <div id="YourElementID">Div</div>



I am assuming that you want to determine if the element has the "hide" class by checking its display style. you don't need to do that, you can easily check its class list by using the following code:

element.classList.contains("hide");

CodePudding user response:

There are several ways of collecting all the elements with display: block and i am not sure, which one performs best - or whether it performs good at all.

If you want all the Element instances of the page, which have a computed style of display: block you can do something like:

var $els = Array.from(document.body.querySelectorAll('*')).filter(function($el) {
    return getComputedStyle($el).display === 'block';
});

Or ES6:

const $els = Array.from(document.body.querySelectorAll('*')).filter($el => getComputedStyle($el).display === 'block');

If you want the Element instances which have display: block literally set in the style-attribute, you have to do something like this:

var $els = Array.from(document.body.querySelectorAll('*')).filter(function($el) {
    return $el.style.display === 'block';
});

I think it would perform better, if the selector in querySelectorAll() would be a little more specific.

Another option would be to use the TreeWalker API, but then you have to do a mutation, because you have to iterate over all the elements and push them to an array:

var $els = [];
walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT);
while (walker.nextNode()) {
    if (getComputedStyle(walker.currentNode).display === 'block') {
        $els.push(walker.currentNode);
    }
}

Once you have all your elements, you can do something with them.

A little bit more information would be helpful, especially what exactly you want to achieve, once you have the elements, because then i could also provide more help. Maybe provide a code example?

  • Related