You are using a array as an object, the difference between getElementbyId
and
getElementsByClassName
is that:
getElementbyId
will return you an object.
getElementsByClassName
will return you an array.
getElementsByClassName
The getElementsByClassName(classNames)
method takes a string that
contains an unordered set of unique space-separated tokens
representing classes. When called, the method must return a live
NodeList
object containing all the elements in the document that
have all the classes specified in that argument, having obtained the
classes by splitting a string on spaces. If there are no tokens
specified in the argument, then the method must return an empty
NodeList.
https://www.w3.org/TR/2008/WD-html5-20080610/dom.html#getelementsbyclassname
getElementById
The getElementById() method accesses the first element with the specified id.
http://www.w3schools.com/jsref/met_doc_getelementbyid.asp
in your code the lines:
1 if (document.getElementByClassName('Div1')) {
2 if (document.getElementByClassName('Div1').style.display == 'block') {
will NOT work as expected: specially the second(2) line,
cos the getElementByClassName
will return an array, and the array will NOT have the style
property, you gonna access each element
by iterating them.
That's why the function getElementById
was working for you, this function will return you the direct object , and so you will be able to access the style
property.
One working code:
function refer(Div1,Div2) {
var elem = document.getElementsByClassName('Div1');
var elems = document.getElementsByClassName('Div2');
for(var i = 0; i < elem.length; i++) {
if (elem[i]) {
if (elem[i].style.display == 'block') {
elem[i].style.display = 'none';
for(var i = 0; i < elems.length; i++) {
elems[i].style.display = 'block';
}
}
}
}
}