Im new to javascript because I skipped it and jumped to jquery and now Im writing a javascript code but I'm having trouble. I have multiple elements with the same class name and below each element is an a-tag. i want to hide/show the element upon clicking the button below it. How can i do this in javascript? (no jquery please).
HTML
<div>
<div class="content">content 1</div>
<a class="show-more" onclick="toggleText();" href="javascript:void(0);">Show more</a>
</div>
<div>
<div class="content">content 2</div>
<a class="show-more" onclick="toggleText();" href="javascript:void(0);">Show more</a>
</div>
<div>
<div class="content">content 3</div>
<a class="show-more" onclick="toggleText();" href="javascript:void(0);">Show more</a>
</div>
CSS
.content {
display: none;
}
Javascript
var status = "less";
function toggleText1() {
if (status == "less") {
document.getElementsByClassName("content")[0].style.display = 'block';
document.getElementsByClassName("show-more")[0].innerText = "See Less";
status1 = "more";
} else if (status1 == "more") {
document.getElementsByClassName("content")[0].style.display = 'none';
document.getElementsByClassName("show-more")[0].innerText = "See More";
status1 = "less";
}
}
in my original code i named my content as content1,content2 and my a-tag as show-more1,show-more2 then my functions as toggleText1,toggleText2 and so on. It works but i find it inefficient. Can you guys guide me to the right path?
Here's one of methods how to solve it. Catch all the links, then use Array#forEach
to iterate over them and bind click
event to every element. Then find the div
element in the parent node and toggle it's class from hidden to visible.
ES6 solution.
var elems = document.getElementsByClassName("show-more");
Array.from(elems).forEach(v => v.addEventListener('click', function() {
this.parentElement.getElementsByClassName('content')[0].classList.toggle('hidden');
}));
.hidden {
display: none;
}
<div>
<div class="content">content 1</div>
<a class="show-more" href="javascript:void(0);">Show more</a>
</div>
<div>
<div class="content">content 2</div>
<a class="show-more" href="javascript:void(0);">Show more</a>
</div>
<div>
<div class="content">content 3</div>
<a class="show-more" href="javascript:void(0);">Show more</a>
</div>
ES5 solution.
var elems = document.getElementsByClassName("show-more");
for (var i = 0; i < elems.length; i++){
elems[i].addEventListener('click', function(){
this.parentElement.getElementsByClassName('content')[0].classList.toggle('hidden');
})
}
.hidden {
display: none;
}
<div>
<div class="content">content 1</div>
<a class="show-more" href="javascript:void(0);">Show more</a>
</div>
<div>
<div class="content">content 2</div>
<a class="show-more" href="javascript:void(0);">Show more</a>
</div>
<div>
<div class="content">content 3</div>
<a class="show-more" href="javascript:void(0);">Show more</a>
</div>