Jump to content

Can't create a button to toggle an h2 heading in html/javascript

Go to solution Solved by RockSolid1106,

 

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")})

 

Hi I'm using a .html file

languages: html, css, javascript
level: beginner

problem:
myFunction2() does not toggle the h2 class ("city")

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>
        Use of The class Attribute in JavaScript
    </title>
</head>
<body>
    <h2>
        Use of the class Attribute in JavaScript
    </h2>
    <p>
        Click the button to hide/show all elements
         with the class name "city":
    </p>

    <button onclick="myFunction()">
        Hide elements
    </button>
    <button onclick="myFunction2()">
        Hide/Show Elements
    </button>
 
    <h2 class="city">
        London
    </h2>
    <p>
        London is the capital of England
    </p>
    <h2 class="city">
        Paris
    </h2>
    <p>
        Paris is the capital of France
    </p>
    <h2 class="city">
        Tokyo
    </h2>
    <p>
        Tokyo is the capital of Japan
    </p>
    <p>
        <b>
            Note:
        </b>
            The element will not take up any space when the display property set to "none".
    </p>
    <script>
        function myFunction()
        {
            var x = document.getElementsByClassName ("city");
            for (var i = 0; i < x.length; i++)
            {
                x[i].style.display = "none";
            }
        }
        function myFunction2()
        {
           var x = document.getElementsByClassName ("city");  
           t.classList.toggle ("city");
           for (var i = 0; i < x.length; i++)
           {
               x[i].style.display = "none";
           }
           for (var i = 0; i > x.length; i--)
           {
               x[i].style.display = "block";
           }
           /*
           if (x.style.display == "none")
           {
                x.style.display = "block";
            }
            else
            {
                x.style.display = "none";
            }
            */
        }
    </script>
</body>
</html>

 

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to post
Share on other sites

The function has to check the current state and act based on that.

<script>
var state = "show";

function myFunction2(){  
  let x = document.getElementsByClassName ("city");
  
  for (let i = 0; i < x.length; i++){
    if(state == "hide"){
      x[i].style.display = "block";                    
    }else {
      x[i].style.display = "none";                    
    }
  }
  
  // state change
  if(state == "hide") state = "show"
  else state = "hide"
}
</script>

ಠ_ಠ

Link to post
Share on other sites

22 minutes ago, shadow_ray said:

The function has to check the current state and act based on that. This is one way to do it:

<script>
SNIP
</script>

Hi, thanks for reply.

So with the normal "Hide elements" button it changes all h2 headings

(3 in this case, London, Paris and Tokyo=)

I want the toggle button to the same if possible.

 

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?) 

 

 I posted to a screenshot that shows the the hide button does

https://snipboard.io/3BgEkU.jpg

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to post
Share on other sites

EDIT: Didn't realize there were other replies on this thread, they loaded in after I posted my reply.

 

It's always a great idea to check your console(Ctrl Shift J).

Here's the error:

image.thumb.png.dd92c2929ec6e2a0d0a3540e4d67cf1f.png

 

From what I can see,

2 hours ago, c0d0ps said:
t.classList.toggle ("city");

you have this line in your code, and "t" is not defined, and JS doesn't know what to do with it. Not sure what you wanted to do with it, probably a typo.

 

2 hours ago, c0d0ps said:

myFunction2() does not toggle the h2 class ("city)

It doesn't toggle the class as you aren't as:

1. You have a reference error as I already mentioned.

2. Even if you fixed that error, it still won't run as getElementsByClassName returns an HTML collection, and you can't perform a classList toggle on that. You have to first convert it to an array, then loop through it, and toggle the class for each item in that array.

 

Here's how the code for that would look:

function myFunction2()
{
	var x = document.getElementsByClassName("city");
	Array.from(x).forEach(p => {[p.classList.toggle("city")}) //creating an array from HTML collection and then looping through the array
           
}

 

 

EDIT:

46 minutes ago, c0d0ps said:

what I actually want is that they should change from h2 to p (h6 might be same size?) 

If all you have to do is change the size, you can do that with JS, instead of changing the element tag(which is not possible anyway)

var x = document.querySelector(".xxxxxxxxx")
x.style.fontSize = "20px" //or whatever value you want

 

Edited by RockSolid1106
On 4/5/2024 at 10:13 PM, LAwLz said:

I am getting pretty fucking sick and tired of the "watch something else" responses. It's such a cop out answer because you could say that about basically anything, and it doesn't address the actual complaints. People use it as some kind of card they pull when they can't actually respond to the criticism raised but they still feel like they need to defend some company/person. If you don't like this thread then stop reading it. See how stupid it is? It's basically like telling someone "shut the fuck up". It's not a clever responsive, it doesn't address anything said, and it is rude. 

 ^

-----

MKBHD is but an Apple propagandist and fanboy. Take his videos with a grain of salt, especially about anything Apple. In his video titled "I Visited Apple's Secret iPhone Testing Labs!", he has shown that he makes no effort to fact check Apple's claims, and takes it at face value. I do not believe he can be trusted as an Reviewer/Influencer.

-----

bruh switch to dark mode its at the bottom of this page

VPN Server Guide

Link to post
Share on other sites

44 minutes ago, RockSolid1106 said:

EDIT: Didn't realize there were other replies on this thread, they loaded in after I posted my reply.

 

It's always a great idea to check your console(Ctrl Shift J).

Here's the error:

image.thumb.png.dd92c2929ec6e2a0d0a3540e4d67cf1f.png

 

From what I can see,

you have this line in your code, and "t" is not defined, and JS doesn't know what to do with it. Not sure what you wanted to do with it, probably a typo.

 

It doesn't toggle the class as you aren't as:

1. You have a reference error as I already mentioned.

2. Even if you fixed that error, it still won't run as getElementsByClassName returns an HTML collection, and you can't perform a classList toggle on that. You have to first convert it to an array, then loop through it, and toggle the class for each item in that array.

 

Here's how the code for that would look:

SNIP

 

 

EDIT:

If all you have to do is change the size, you can do that with JS, instead of changing the element tag(which is not possible anyway)

SNIP

 

Thanks for reply

1.

Nothing happens if I try to press Ctrl Shift J in Visual Studio Code - but it'll keep it in mind when I find the right shortcut

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 

3.

I also tried changing the character size to 20px with JavaScript and nothing happened.

    <script title="myFunction2">
        var state = "show";

        function myFunction2()
        {
            var x 
            = document.getElementsByClassName("city")
            = document.querySelector(".xxxxxxxxx");
            x.style.fontSize = "20px";
            Array.from(x).forEach(p => {[p.classList.toggle("city")]})
            /* 
            Creating an array from HTML collection and 
            then looping through the array
            */
        }
    </script>

 

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to post
Share on other sites

Just now, c0d0ps said:

Nothing happens if I try to press Ctrl Shift J in Visual Studio Code - but it'll keep it in mind when I find the right shortcut

Ctrl Shift J in the browser 😛

Or you can inspect the page, then go to the console tab. Both are functionally the same.

On 4/5/2024 at 10:13 PM, LAwLz said:

I am getting pretty fucking sick and tired of the "watch something else" responses. It's such a cop out answer because you could say that about basically anything, and it doesn't address the actual complaints. People use it as some kind of card they pull when they can't actually respond to the criticism raised but they still feel like they need to defend some company/person. If you don't like this thread then stop reading it. See how stupid it is? It's basically like telling someone "shut the fuck up". It's not a clever responsive, it doesn't address anything said, and it is rude. 

 ^

-----

MKBHD is but an Apple propagandist and fanboy. Take his videos with a grain of salt, especially about anything Apple. In his video titled "I Visited Apple's Secret iPhone Testing Labs!", he has shown that he makes no effort to fact check Apple's claims, and takes it at face value. I do not believe he can be trusted as an Reviewer/Influencer.

-----

bruh switch to dark mode its at the bottom of this page

VPN Server Guide

Link to post
Share on other sites

1 minute ago, shadow_ray said:

Oh yeah, a class toggle is much better.

It is, but it won't work as a toggle. You see, the elements are being grabbed by using a class name of 'city', and removing the class 'city' when toggling will mean it won't grab the element the next time, because the element no longer belongs to that class.

 

A way to fix this could be assigning all the h2 another class like:

<h2 class="city myelement"></h2>

 

And then calling the elements with that class:

Array.from(document.getElementsByClassName("myelement")).forEach(p => () {p.classList.toggle("city") })

 

On 4/5/2024 at 10:13 PM, LAwLz said:

I am getting pretty fucking sick and tired of the "watch something else" responses. It's such a cop out answer because you could say that about basically anything, and it doesn't address the actual complaints. People use it as some kind of card they pull when they can't actually respond to the criticism raised but they still feel like they need to defend some company/person. If you don't like this thread then stop reading it. See how stupid it is? It's basically like telling someone "shut the fuck up". It's not a clever responsive, it doesn't address anything said, and it is rude. 

 ^

-----

MKBHD is but an Apple propagandist and fanboy. Take his videos with a grain of salt, especially about anything Apple. In his video titled "I Visited Apple's Secret iPhone Testing Labs!", he has shown that he makes no effort to fact check Apple's claims, and takes it at face value. I do not believe he can be trusted as an Reviewer/Influencer.

-----

bruh switch to dark mode its at the bottom of this page

VPN Server Guide

Link to post
Share on other sites

13 minutes ago, RockSolid1106 said:

1.

<h2 class="city myelement"></h2>

2.

And then calling the elements with that class:

SNIP

 

1. Completed

 

full script code below

    <script title = "Example 3">
        Array
        .from
        (document.getElementsByClassName("myelement"))
        .forEach
        (p => ()
        {p.classList.toggle("city")})
    </script>

2. 

Got this error from it 

image.png.8fed320448b8ea9a51a7219423056771.png

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to post
Share on other sites

 

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")})

 

On 4/5/2024 at 10:13 PM, LAwLz said:

I am getting pretty fucking sick and tired of the "watch something else" responses. It's such a cop out answer because you could say that about basically anything, and it doesn't address the actual complaints. People use it as some kind of card they pull when they can't actually respond to the criticism raised but they still feel like they need to defend some company/person. If you don't like this thread then stop reading it. See how stupid it is? It's basically like telling someone "shut the fuck up". It's not a clever responsive, it doesn't address anything said, and it is rude. 

 ^

-----

MKBHD is but an Apple propagandist and fanboy. Take his videos with a grain of salt, especially about anything Apple. In his video titled "I Visited Apple's Secret iPhone Testing Labs!", he has shown that he makes no effort to fact check Apple's claims, and takes it at face value. I do not believe he can be trusted as an Reviewer/Influencer.

-----

bruh switch to dark mode its at the bottom of this page

VPN Server Guide

Link to post
Share on other sites

19 hours ago, RockSolid1106 said:

 

You said:

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.

SNIP

 

 

 

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:

SNIP

Then, you can loop through the HTML collection:

SNIP

 

PS:

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:

SNIP

 

It works now thank you.

 

This toggle button now does the same as the hide button

   <script title="Example 1" name="success">
        var state = "show";
        function myFunction2()
        {
            var x = document.getElementsByClassName ("city"); // getting elements

           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
               }
           }
        }
    </script>

 

PC  Specs 2022:

Spoiler
  • CPU
    AMD Ryzen R9 5900x @ 5.1GHz - Auto OC
  • Curve Optimizer Magnitude: -20
  • Motherboard
    ASUS ROG STRIX x570-F Gaming
  • RAM
                                        Kingston Fury 32GB DDR4 3200MHz 16x2GB
  • GPU
    MSI 3070 8GB Ventus 2x OC
  • Case
    LIAN LI LANCOOL MESH II Mesh RGB Black
  • Storage
    Kingston NV1 2TB M.2. NVMe
  • PSU
    Seasonic Focus GX 850w 
  • Display(s)
    MSI OPTIX MAG 251RX IPS 240hz & ASUS MG248Q Vertical 144hz & Dell 60hz
  • Cooling
    NZXT Kraken x73 360mm
  • Keyboard
    Tt eSports Meka G1
  • Mouse
    Logitech G Pro Wireless
  • Operating System
    -Windows 10 Professional 64bit
Link to post
Share on other sites

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 account

Sign in

Already have an account? Sign in here.

Sign In Now

×