Home > Enterprise >  Changing an <a> tag with javascript
Changing an <a> tag with javascript

Time:05-02

I need to change an anchor tag from this

<a href="#" id="masini">Mașini <i ></i></a>

to this

<a href="#" id="masini">Mașini <i ></i></a>

when the screen gets smaller. Basically to be responsive. I need to use javascript btw.

I tried the code bellow but it's not working.

if(window.innerWidth < 1130px)
        {
            var replace = "Mașini"
            replace  = "<i ></i>";
            document.getElementById("masini").innerHTML = replace;
        }

CodePudding user response:

I'd recommend targeting the <i> element and changing it's class:

if (window.innerWidth < 1130) {
    const iElement = document.querySelector("#masini i");
    iElement.classList.replace("bi-caret-right", "bi-caret-down");
}

CodePudding user response:

It would help to do the following:

if (window.innerWidth < 1130) {
  document.getElementById("masini").className = "bi bi-caret-down";
}
<a href="#">Mașini <i id="masini" ></i></a>

CodePudding user response:

You need to delimit your double quotes or wrap with single quotes.

replace  = '<i ></i>';

OR:

replace  = "<i class=\"bi bi-caret-down\"></i>";
  • Related