Reputation: 2277
I'm trying to add a class to a paragraph with javascript. but it ends only passing the class to wrong id. I would like to change changes on the <p id="para" class="para" >NAV One</p>
but at the moment it only changes the background of the list.
Any ideas ?
function toggle_visibility(id) {
var thelist = document.getElementsByClassName("alist");
var para = document.getElementsByClassName("para");
for (var i = 0; i < thelist.length; i++) {
thelist[i].style.display = 'none';
}
var e = document.getElementById(id);
var para = document.getElementById(id);
if(e.style.display == 'block') {
e.style.display = 'none';
} else {
para.className += " " + 'active';
e.style.display = 'block';
}
}
JSfiddle. http://jsfiddle.net/FqqhY/4/
Upvotes: 0
Views: 348
Reputation: 18349
I presume you want your toggle function to look more like this
function toggle_visibility(hyp, id) {
// hide all lists
var allLists = document.getElementsByClassName('alist');
for (var i = 0; i < allLists.length; i++)
allLists[i].style.display = 'none';
// deactive all paragraphs
var allParas = document.getElementsByClassName('para');
for (var i = 0; i < allParas.length; i++)
allParas[i].className = 'para';
// select the clicked hyper link and its child paragraph
var list = document.getElementById(id),
para = hyp.getElementsByClassName('para')[0];
// activate the current para and show the list
para.className = 'para active';
list.style.display = 'block';
}
You also need to pass this
in as the first argument to the toggle function along with the corresponding list id
<a href="#" onclick="toggle_visibility(this, 'list1');">
See fiddle
Upvotes: 1