getAttribute of element with the state (.active)

display name

I am having trouble checking the active state of an element attribute. I tried below but it returned false even though the element has the attribute in an active state - (.c-banner.active is present)

ngAfterViewInit() {
    const bannerElm = document.getElementById("banner");
    const isActive = bannerElm && bannerElm.getAttribute("class")
      .indexOf("c-banner.active") !== -1;  // returned false
}
Sushanth --

You can use classList.contains method to check if the element has the active class.

ngAfterViewInit() {
    setTimeout(() => {
        const isActive = bannerElm &&
                         bannerElm.classList.contains('c-banner') &&
                         bannerElm.classList.contains('active');
    }, 1000);
}

[UPDATED] wrap it within setTimeout() and it worked! In case anyone else is stuck with the component initialization orders issue that I had previously.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to apply style to child of element with active state

React: Secondary element controlling active state

Nav Menu Active Element and State Management Issue

How to set the hover state equals the active state with li clearfix element using ui-sref-active="active"

Bootstrap 3 navbar anchor element is not styled properly on the active/focus state

How to remove an elements active state when a sub element is clicked

How to add active class/state for li element in ReactJS?

Active state pseudo class and Adjacent element selector combined on IE

track boolean state of each element in array and change styles if active react

getAttribute() versus Element object properties?

In JavaScript getAttribute from li element works partially

JavaScript Element.value vs Element.getAttribute("value")

menu jquery state is-active is-not-active

Move element when :active

Active NavLink to parent element

Cancel :active element styling

Switch <li> active element

Set react element active

Switch current "active" element

getAttribute is not a function - can't iterate loop for every element

Cannot get the text of an element. Tried getText() and getAttribute("innerHTML")

How would you compare the value of element.getAttribute() to a String in protractor?

Custom Element class: this.getAttribute('data-*') returns null

getAttribute isPermaLink is returning null for element in rss feed with Protractor

Detect :hover:active:focus state

toggle active state with hooks react

changing active state of buttons in react

How to add active state to tabs

Bootstrap navbar Active State not working