I’m a newbie to HTML, CSS and JavaScript and I’d like some help.
Let say I have 3 buttons and 3 paragraphs
<head>
<style>
.hidden {
display: none;
}
</style>
</head>
<body>
<button>A</button>
<button>B</button>
<button>C</button>
<br>
<p>A</p>
<p>B</p>
<p>C</p>
</body>
I want to create a js function that hides all paragraphs except the one with the same letter as the button, using a CSS rule that apply the class "hidden".
I tried many things but all I can do is to toggle the class hidden to all paragraphs. Can someone explain me how I can do that please?
Thank you!
Here’s the file I was using to test anything I could think of to find a solution
<!doctype html>
<html>
<head>
<title></title>
<style>
.hidden {
display: none;
}
</style>
</head>
<body>
<div class="button">
<button class="a" onClick="toggle(this,id)">a</button>
<button class="b" onClick="toggle(this,id)">b</button>
<button class="c" onClick="toggle(this,id)">c</button>
</div>
<div class="main">
<div class="a text">
<p>a</p>
</div>
<div class="b text">
<p>b</p>
</div>
<div class="c text">
<p>c</p>
</div>
</div>
<script>
function toggle(clicked,id) {
var el = document.querySelectorAll(".text");
var length = el.length;
for (let i=0; i<length; i++){
el[i].classList.add("hidden");
}
}
</script>
</body>
</html>
To avoid switching from different files I wrote all the CSS and JS in the HTML file.
2
Answers
I tried to put the respective comment before every JavaScript code, hope it helps you.
The part
para${letter}
simply checks for letterA, B, C
and maps it to para i.e;paraA
, etc. In JavaScript, Template literals are literals delimited with backtick (`) characters, allowing for multi-line strings, string interpolation with embedded expressions, and special constructs called tagged templates.It could be done in a quite simple way using the
details
element, with the use of hisopen
attribute.Further enhancement can be done by using CSS!
Source