Get one class in a function with index for a menu with underline hover

Viewed 119

I'm working on an hover effect for a menu which worked well while using ID's but I can't figure how to do the same with multiples classes.

The function is to get the width of the text and apply an underline on hover with the same length. It would be nice if I could do it without jQuery.

Here is the demo : JSFiddle

Working with ID's:

function textWidth() {

    var TextDiv = document.getElementById("link-menu");
    var txtWidth = (TextDiv.clientWidth + 1);
    document.getElementById("underline").style.width = txtWidth + 'px';
}
function textWidthInitial() {

    document.getElementById("underline").style.width = '0px';
}

Attempts with classes #1:

function textWidth() {


    var linkDiv = document.getElementsByClassName("link-menu");
    var underlineDiv = document.getElementsByClassName("underline");
    var i;
    for (i = 0; i < linkDiv.length; i++) {
        var txtWidth = (linkDiv[i].clientWidth + 1);
        underlineDiv[i].style.width = txtWidth + 'px';
    }
}

Attempts with classes #2:

function textWidth() {

    var clsLinkMenu = document.querySelectorAll('.underline, .link-menu');
    var i;
    for (i = 0; i < clsLinkMenu.length; i++) {
        var txtWidth = (clsLinkMenu[i].clientWidth + 1);
        document.getElementsByClassName("link-menu")[i].style.width = txtWidth + 'px';
        document.getElementsByClassName("underline")[i].style.width = txtWidth + 'px';
    }
}
1 Answers
Related