Kevin.a Kevin.a - 1 month ago 6
HTML Question

Change link color on hover javascript only

Is it possible to change a certain on hover over another certain item.

For example:

<li>
<a href="#">test</a>
</li>


JS

var list = document.getElementById('li');
var link = document.getElementById('a');

list.onmouseover = function() {
link.style.color = "#8080ff";
}


If i hover over the
li
item I want the text inside the
a
tag to change, but this code is not working.

I cant use css or jquery library.

http://jsfiddle.net/Nt8Pq/40/

Answer

Your code looks for elements with ids and you have not ids. You would need to select them by the tag name and loop over the collection. And than you would need to find the anchor that is inside of the collection.

var menu = document.getElementById("menu");
var lis = menu.getElementsByTagName("li");

for (var i = 0; i < lis.length; i++) {
  var li = lis[i];
  li.addEventListener("mouseover", function() {
    this.getElementsByTagName("a")[0].style.color = "#8080ff";
  });
  li.addEventListener("mouseout", function() {
    this.getElementsByTagName("a")[0].style.color = "#000000";
  });
}
<ul id="menu">
  <li>
    <a href="#">test</a>
  </li>
  <li>
    <a href="#">test</a>
  </li>
  <li>
    <a href="#">test</a>
  </li>
</ul>

In the end this is a lot of code to implement

ul li:hover a {
    color : "#8080ff";
}

SO you could just inject a CSS rule if you are not able to actually add styles to the page...

var sheet = window.document.styleSheets[0];
sheet.insertRule('#menu li:hover a { color: #8080ff; }', sheet.cssRules.length);
<ul id="menu">
  <li>
    <a href="#">test</a>
  </li>
  <li>
    <a href="#">test</a>
  </li>
  <li>
    <a href="#">test</a>
  </li>
</ul>

Comments