Diogo Neiss
Diogo Neiss

Reputation: 117

Change color of <a> item with querySelectorAll and specific innerHTML

I need to change a menu dropdown item only if it is "Saldos".

I'm using a array to select all the parent elements and passing it to a function, which selects the inside and checks if it contains the text.

However it does not work, even if I put if(1).

var menuArrayHeader = document.querySelectorAll(".drawer__nav-item");

menuArrayHeader.forEach(verificarVermelho)

function verificarVermelho(menuItemParent){
    var menuItem =menuItemParent.querySelector(".drawer__nav-link");
    console.log(menuItem.innerHTML);

    if(menuItem.innerHTML.includes("Saldos")){
        menuItem.style = "color: red !important;";
    }
}

The website I'm testing the code on is https://www.karitaideale.com.br/pages/karita

Example

Upvotes: 0

Views: 961

Answers (2)

Check for .innerText instead of innerHTML to find the actual text inside that container.

menuArrayHeader.forEach(verificarVermelho)

function verificarVermelho(menuItemParent){
    var menuItem = menuItemParent.querySelector( ".drawer__nav-link" );
    console.log( menuItem.innerText );

    if( menuItem.innerText === "Saldos" ) ) {
        $( menuItem ).attr( 'style', 'color: red !important;' );
    }
}

Also, keep in mind that you need to set the color property on the a element child inside the li to override the already set property color: #000 on that a element.

Screenshots from the "Karita" website:

enter image description here

Upvotes: 1

Ruan Mendes
Ruan Mendes

Reputation: 92294

HTMLELement.style is read-only, you must set its sub properties. In your case,

menuItem.style.color = "red";

See https://developer.mozilla.org/en-US/docs/Web/API/ElementCSSInlineStyle/style#Setting_styles

Styles should not be set by assigning a string directly to the style property (as in elt.style = "color: blue;"), since it is considered read-only, as the style attribute returns a CSSStyleDeclaration object which is also read-only. Instead, styles can be set by assigning values to the properties of style

Upvotes: 0

Related Questions