Can't color a selected <a> tag

95 views Asked by At

I'm working on a full javascript menu.

I'm trying to change the color of <li> or <a> item depending of the offsetTop of the user. Ask me if it's not understandable.

Menu

var menu = document.getElementById('header');
var work = document.getElementById('work');
var who = document.getElementById('who');
var contact = document.getElementById('contact');
var offsetWork = work.offsetTop - 60;
var offsetWho = who.offsetTop - 60;
var offsetContact = contact.offsetTop - 60;
var ul = document.getElementsByTagName('ul')[0];
var li = ul.getElementsByTagName('li');

setInterval(function(){
    var ul = document.getElementsByTagName('ul')[0];
    var li = ul.getElementsByTagName('li');

    if(getCurrPos() >= offsetWork){
        menu.style.display = "block";
    }else if(getCurrPos() <= offsetWork){
        menu.style.display = "none";
    }

    if(offsetWork <= getCurrPos() <= offsetWho){
        li[1].style.backgroundColor = '#00a9c6';
        //li[1].getElementsByTagName('a').style.color = '#fff';
    }else {
        li[1].style.backgroundColor = '#fff';
    }

    if(offsetWho <= getCurrPos() <= offsetContact){
        li[2].style.backgroundColor = '#00a9c6';
        //li[2].getElementsByTagName('a').style.color = '#fff';
    }else {
        li[2].style.backgroundColor = '#fff';
    }

    if(getCurrPos() >= offsetContact){
        li[3].style.backgroundColor = '#00a9c6';
        //li[3].getElementsByTagName('a').style.color = '#fff';
    }else {
        li[3].style.backgroundColor = '#fff';
    }

}, 100);

All the commented line doesn't works and i don't know why because It's finding the [a] item when doing li[1].getElementsByTagName('a');

Thank you for help,

Maël.

1

There are 1 answers

1
Deep On BEST ANSWER

use

li[3].querySelector('a').style.color = '#fff';

querySelector returns the first Element within the all elements selected by the selector

getElementsByTagName return a collection of all elements matching the selector hence you can not access the element with the syntax like li[2].getElementsByTagName('a').style.color