...

View Full Version : Document.getElementById problem



tqmd1
11-21-2011, 09:49 AM
Dear Sir,

These codes work fine




<li><a href="" onclick="document.getElementById('div2').style.display='none';return false">Hide Div 2</a></li>


If use these line, then it do not work

<li><a href="" onclick="document.getElementById('div2','div3','div4','div5').style.display='none';return false">Hide Div 2</a></li>



I used more than one div in it.

Complete discussin is here
http://www.webdevforums.com/showthread. ... w-Hide-Div

Please help

moon-safari
11-21-2011, 10:13 AM
I used more than one div in it.


...and exactly that is the problem. getElementById returns one element for one given id. So what you need is a for-loop:


<li><a href="" onclick="hide()">Hide Div 2</a></li>

...and the javascript function:


function hide()
{
for (var i = 2; i<=5; i++)
{
document.getElementById('div'+i).style.display='none';
}
return;
}

tqmd1
11-21-2011, 10:47 AM
sir if id is like this

div1, mydiv,product,about

Then how to add reference in


document.getElementById('div'+i).style.display='none';

moon-safari
11-21-2011, 11:32 AM
You could then define an array:



var ids = ["div1", "mydiv", "product", "about"];

function hide()
{
for (var i = 0; i < ids.length; i++)
{
document.getElementById(ids[i]).style.display='none';
}
return;
}

or you write every line:



function hide()
{
document.getElementById("divs1").style.display='none';
document.getElementById("mydiv").style.display='none';
(....)
return;
}


or you find another possibility to select your div elements. Maybe you want to hide all the div elements of one specific parent, then you could use:



var divs = parent.children;

function hide()
{
for (var i = 0; i < divs.length; i++)
{
divs[i].style.display='none';
}
return;
}

you could also check out the functions "querySelector" and "querySelectorAll", which let you select Elements with a CSS query string (like "#id > div"). In many cases it is easier to create a clean and logic HTML structure, which let you use Selectors like these, than select every single Element by its ID (even IDselection might be faster). But for the beginning the array-method should definitly do it.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum