skip to Main Content

When I try to set the color of the link element, using the class name like this :


      var link = document.createElement('a');
      link.classList.add('f');
 .f {
    color: white !important;

  }
   

The link still remains blue
but when I apply it generally using the anchor tag

 a {
    color: white !important;

  }
   


the link text is turned to white, why is that ? What should I do ?

I wanted the link color of my anchor tag to be displayed white, but when I style it with my classname it gets displayed blue, but if I use the general anchor tag the style is applied

4

Answers


  1. Here You Go

    function addElement() {
                // create a new anchor element
                const newAnchor = document.createElement("a");
    
                // and give it some content
                const newContent = document.createTextNode("Hi there and greetings!");
    
                // add the text node to the newly created anchor
                newAnchor.appendChild(newContent);
                newAnchor.classList.add('f');
    
                // add the newly created element and its content into the DOM
                const currentDiv = document.getElementById("div1");
                document.body.insertBefore(newAnchor, currentDiv);
            }
    .f {
                color: red !important;
                cursor: pointer;
            }
    <button onclick="addElement()">Click for generate anchor</button>
        <div id="div1"></div>
    Login or Signup to reply.
  2. document.getElementById("a1").style.color = "red";
    <a href='#' id="a1">Change Text Color</a>
    you can use inline style to change the text color inside anchor tag.<br>
    <a href="#" style="color: red;">Hello</a>
    Login or Signup to reply.
  3. The problem here is the ‘a’ attribute is not getting the class value.

    So instead we can use the following logic to set the class value to ‘a’ tag:

    let link = document.createElement('a');
    link.innerText = "your link";
    link.classList.add('f');
    link.setAttribute('href', '#');
    document.body.appendChild(link);
    body{
      background:black;
    }
    .f{
      color: white;
    }
    <a href="#">other link</a>
    <br>
    <br>

    Also no need to add !important anymore

    Login or Signup to reply.
  4. Firstly, you should always ignore !important it should not be used frequently until it is important, as it gives element the highest specificity and makes CSS harder to maintain. and in this code

    var link = document.createElement('a');
    link.classList.add('f');
    

    you are only creating an element but it is not made in DOM you should append it in the body first like this

    document.body.append(link)
    

    Now your anchor is added in the DOM with class first it was not added. Now your CSS using class selector will work.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search