Skip to content Skip to sidebar Skip to footer

Hide And Show Elements By Clicking On A Link With Java Script Without Jquery

I really need some help, I wanna know what's the best way to hide and show elements by clicking on a link just using Java Script without Jquery. So, when I click on the 'Link 1' n

Solution 1:

Just try to fix your code.

  1. add missing [0] after document.getElementsByClassName("content")
  2. change getElementsByClassName() to querySelectorAll() in order to work in IE8
  3. change variable i in navList.children[i].onclick to remembered variable index
  4. change variable i start value to 0
  5. pass index + 1 as a dest of mudaConteudo() since index start with 0 but your content ids start with 1

Here the result:

window.onload = function () {
    functionmudaConteudo(elm, dest) {
        var divs = document.querySelectorAll(".content")[0].getElementsByTagName('div');
        for (var i = 0, len = divs.length; i < len; i++) {
            divs[i].style.display = "none";
        }
        document.getElementById('cont' + dest).style.display = "block";
    }
    var navList = document.querySelectorAll(".links")[0];
    for (var i = 0, len = navList.children.length; i < len; i++) {
        (function(index){
            navList.children[index].onclick = function () {
                mudaConteudo(this, index + 1);
                document.querySelectorAll(".active")[0].removeAttribute("class");
                this.className = "active";
            };
        })(i);
    }
}

Hope this help.

Solution 2:

Try this:

var list = document.getElementsByTagName('ul');
var links = list[0].getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
    links[i].onclick = function () {
        var target = this.innerHTML.substr(-1);
        var divs = document.getElementsByClassName("content");
        var subdivs = divs[0].getElementsByTagName('div');
        for (var i = 0; i < subdivs.length; i++) subdivs[i].style.display = 'none';
        document.getElementById('cont' + target).style.display = 'block';
    };
};

jsFiddle example

Post a Comment for "Hide And Show Elements By Clicking On A Link With Java Script Without Jquery"