Hi need some help from Javascript guru, I am trying the complete the skill test events 1, I try to use the toggle() bewteen 2 style, but not works
the code I added on:
function myToggle() {
var element = document.getElementsByClassName(“preview”);
element.classList.toggle(“.p”);
}
btn.addEventListener(“click”,myToggle);
source code from github:
Events: Task 1
p {
color: purple;
margin: 0.5em 0;
}
* {
box-sizing: border-box;
}
button {
display: block;
margin: 20px 0 20px 20px;
}
</style>
<link rel="stylesheet" href="../styles.css" />
<section class="preview">
</section>
<button class="off">Machine is off</button>
My question: how to add the toggle function when click the button
Hello @Frankie_BNE
there no guru here just learner same as you
here my notice
-
getElementsByClassName
return array not just single element even if it is an array of one element so still array
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
when you need to know what thee function return go to https://developer.mozilla.org and search for the function you want and you will get detailed page with example to help you
- toggle will remove the class from the class list if it exist but add it if it not exist https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/toggle
so for the first time the button class="off p"
then after second click it will remove it by the way you write the name of the class without the .
the task ask ask you to change the text content from Machine is off
to Machine is on
and vise versa after each click
if you need me to explain it in better way let me know
but share your full code in one of the online service like codepen.io
and have a nice day 
1 Like