Search code examples
javascripthtmlcsshref

Comparing attribute of an anchor's href with "#"?


I want to change the css properties of all anchors with href set to "#".

<div class="mlItems">
    <a href="#">Home</a>
</div>
<div class="mlItems">
    <a href="applets.html">Applets</a>
</div>
<div class="mlItems">
    <a href="tools.html">Tools</a>
</div>
<div class="mlItems">
    <a href="gallery.html">Gallery</a>
</div>
<div class="mlItems">
    <a href="tutorials.html">Tutorials</a>
</div>
<div class="mlItems">
     <a href="fun.html">Fun</a>
</div>
<div class="mlItems">
      <a href="about.html">About</a>
</div>

so i searched the elements using their tag name and compare the href with "#" using a for loop. Then changed the style properties of the element using javascript.

function setnavstat(){
var menul = document.getElementsByTagName("a");
for(var i = 0;i < menul.lenght;i++){
    if(menul[i].getAttribute("href") == "#"){ 
         menul[i].style.color = "#000000";
       } 
     }
}

but this doesn't seem to work. help me. thanks in advance. it would help if the response be in JavaScript only.


Solution

  • You don't need to use JavaScript, you can do it in pure CSS :

    a[href="#"]{
        color: #000000;
    }
    <div class="mlItems">
        <a href="#">Home</a>
    </div>
    <div class="mlItems">
        <a href="applets.html">Applets</a>
    </div>
    <div class="mlItems">
        <a href="tools.html">Tools</a>
    </div>
    <div class="mlItems">
        <a href="gallery.html">Gallery</a>
    </div>
    <div class="mlItems">
        <a href="tutorials.html">Tutorials</a>
    </div>
    <div class="mlItems">
         <a href="fun.html">Fun</a>
    </div>
    <div class="mlItems">
          <a href="about.html">About</a>
    </div>