-1

I'm having problem about changing CSS display property to "none" using javascript

Here is my code:

<div class="mydiv" onClick="clickDiv1()">hello</div>
<div class="mydiv" onClick="clickDiv2()">hi</div>
<div class="mydiv" onClick="clickDiv3()">goodbye</div>

And here is my script:

 function clickDiv1() { 
alert('You clicked the first div!');
document.getElementByClassName('mydiv').style.display="none";
}

 function clickDiv2() {
alert('You clicked the second div!');
document.getElementByClassName('mydiv').style.display="none";
}

 function clickDiv3() {
alert('You clicked the second div!');
document.getElementByClassName('mydiv').style.display="none";
}

What I wanted is, different div alert different text when click on it, but when click on any div all div is invisible.

When I click on my div, the alert is execute but style doesn't change.

Why it doesn't work? Please help me!!

Anakin
  • 1,233
  • 1
  • 14
  • 20

2 Answers2

1

The difference is when you use class to document.getElementByClassName('mydiv'), it returns you an array. So you need to use document.getElementByClassName('mydiv')[i], where i is the array index. But document.getElementById('div3') will give you only one item.

document.getElementByClassName('mydiv')[0].style.display="none";

or

document.getElementById('div3').style.display="none"; 

should work.

Abhitalks
  • 27,721
  • 5
  • 58
  • 81
Rohith K
  • 1,433
  • 10
  • 15
  • Not exactly an *array*, but a live *nodeList*, which is an array-like object containing all the matched elements. – Abhitalks Jan 05 '15 at 06:47
  • document.getElement**s**ByClassName('mydiv') rather than document.getElementByClassName('mydiv') – Roy Grubb Oct 19 '20 at 13:41
0

The correct Javascript method to use to select HTML elements is getElementsByClassName().

This will return an array of all the elements in the DOM with that class name, which you need to loop through and individually set the display to none.

For your example, this code would work:

function hideAll() {
  var elems = document.getElementsByClassName('mydiv');
  for (i = 0; i < elems.length; i++) {
    var elem = elems[i];
    elem.style.display = 'none';
  }
}

function clickDiv1() {
  alert('You clicked the first div!');
  hideAll();
}

function clickDiv2() {
  alert('You clicked the second div!');
  hideAll();
}

function clickDiv3() {
  alert('You clicked the third div!');
  hideAll();
}
alexpls
  • 1,914
  • 20
  • 29