I am trying to show/hide text with the same class. I tried the following code that hides only the first id getElementById
, which makes me decide to remove all IDs
and just keep the class
.
The text/words to be hidden are in different positions in the page (so I can’t just add a whole div
around it, as I want to keep other text visible all the time).
I want to use getElementsByClassName
instead, but I can’t seem to get it working.
function showhide() {
var div = document.getElementById("newpost");
div.classList.toggle('hidden');
}
.hidden{
display : none;
}
<button id="button" onclick="showhide()">Click Me</button>
<span id="newpost" class="hidden"><p>text 1</p></span>
<span id="newpost" class="hidden">text 2</span>
<span id="newpost" class="hidden"><p>text 3</p></span>
3
Answers
if you try to do this with getElementsByClassName the problem is if you access elements with classname and toogles the class first time it will remove that class and when you click again you are not supposed to access that class.
the possible solution would be two create two class name .hidden and .visible and add respective class onclick event or else you can also do it by accessing span tag directly
You need two classes:
hidable
in the example below)hidden
in the example).I would assign to each element whose display needs to be toggled a class such as
demo
that can be styled any way you want (except hidden) or not styled at all. I would then alternate adding or removing a classhidden
: