Can't create a button to toggle an h2 heading in html/javascript
10 minutes ago, c0d0ps said:2.
I tried to convert it into an array and it doesn't seem to do the same as the "hide" button
(note the picture in the reply above for reference point)
and also doesn't seem to have a "show" function
You said:
1 hour ago, c0d0ps said:I think I wrote wrong in the main post that it was supposed to "hide" h2 headings
what I actually want is that they should change from h2 to p (h6 might be same size?)
Which made me think you didn't want to toggle hide/show the elements.
In that case, you can use the same array and loop through it, this time checking if display is none on that element, and then applying the CSS property respectively.
function myFunction2() { var x = document.getElementsByClassName ("city"); //getting the elements with class "city" for (var i=0; i < x.length; i++) //looping through the HTML collection if (x[i].style.display == "none") //check if display is none { x[i].style.display = "block"; // if yes, set display to block } else { x[i].style.display = "none"; //else, set display to none } }
13 minutes ago, c0d0ps said:I also tried changing the character size to 20px with JavaScript and nothing happened.
14 minutes ago, c0d0ps said:var x = document.getElementsByClassName("city") = document.querySelector(".xxxxxxxxx"); x.style.fontSize = "20px";
Uhm.. You had to replace .xxxxxxx with your class name.
The syntax is also wrong here, my bad, I didn't realize you were a beginner and I shouldn't have skipped over parts of the code.
You will first have to grab the elements like so:
var x = document.getElementsByClassName("city"); //getting elements
Then, you can loop through the HTML collection:
for(var i = 0; i<x.length; i++){ //looping through the HTML collection x[i].style.fontSize = "20px"; //setting font size for each item of the collection }
PS:
5 minutes ago, c0d0ps said:2.
Got this error from it
Apologies. I didn't run the code, and the syntax I wrote was wrong. There shouldn't be parenthesis after p =>
The line should look like:
.forEach(p => {p.classList.toggle("city")})

Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now