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.
- add missing
[0]
afterdocument.getElementsByClassName("content")
- change
getElementsByClassName()
toquerySelectorAll()
in order to work in IE8 - change variable
i
innavList.children[i].onclick
to remembered variableindex
- change variable
i
start value to0
- pass
index + 1
as a dest ofmudaConteudo()
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';
};
};
Post a Comment for "Hide And Show Elements By Clicking On A Link With Java Script Without Jquery"