I am trying to show/hide divs with button click. I couldn't find something that works. I know how to do it with jquery but I have to use javascript for this one. What I tried is below
JavaScript
Protectia capului
Protectia mainilor
Protectia fetei
Protectia picioarelor
Protectia corpului
Protectia respiratorie
Protectia electrica
Section 1
Section 2
Section 3
Section 4
Section 5
Section 6
Section 7
var buttons = document.querySelectorAll('.btn');
var divs = document.querySelectorAll('.div');
for (var i = 1; i

Naimish MakwanaRank #324 · 7.7K reputationPosted Feb 9, 2023, 1:51 AM EST
Hello Marius,
Change script code as below:
.div { display: none; } Protectia capului Protectia mainilor Protectia fetei Protectia picioarelor Protectia corpului Protectia respiratorie Protectia electrica Section 1 Section 2 Section 3 Section 4 Section 5 Section 6 Section 7 var btns = document.querySelectorAll(".btn"); var sections = document.querySelectorAll(".div"); btns.forEach(function(btn) { btn.addEventListener("click", function() { var id = btn.id; var sectionId = id.substring(id.length - 1); sections.forEach(function(section) { section.style.display = "none"; }); document.getElementById("section" + sectionId).style.display = "block"; }); });Thanks
Naimish Makwana
Naimish MakwanaRank #324 · 7.7K reputationPosted Feb 8, 2023, 11:02 PM EST
Hello Marius,
Please use below code.
Protectia capului Protectia mainilor Protectia fetei Protectia picioarelor Protectia corpului Protectia respiratorie Protectia electrica Section 1 Section 2 Section 3 Section 4 Section 5 Section 6 Section 7 var buttons = document.querySelectorAll(".btn"); var divs = document.querySelectorAll(".div"); for (var i = 0; iWorking Example : https://codepen.io/Naimishcon/pen/abjredx
Thanks
Naimish Makwana
Muhammad Imran AnsariRank #326 · 7.6K reputationPosted Feb 9, 2023, 12:03 AM EST
Hi Marius,
You can achive this through 'data-toggle' attribute that specifies the id of the div that it should toggle. The event listener retrieves the 'data-toggle' attribute of the button that was clicked and uses it to find the corresponding div. Here is the code
I have also created a jsFiddle for you click the link to check: https://jsfiddle.net/2eym9jg8/
Marius VasileRank #785 · 2.9K reputationPosted Feb 9, 2023, 1:26 AM EST
Thank you both, your code is working fine but hiw do I hide the other sections on button click. Like btn 1 show section 1 and hide all others and so on?
Muhammad Imran AnsariRank #326 · 7.6K reputationPosted Feb 9, 2023, 2:16 AM EST
Have you checked my code and fiddle?
Initially all sections are hide and only that section will show which is crosspondent button click.
Marius VasileRank #785 · 2.9K reputationPosted Feb 9, 2023, 2:47 AM EST
Thank you Naimish that did the trick