JQuery's Add/Remove Class Functionality Fails to Execute

After mastering the use of JQuery to manipulate CSS properties with buttons, I am now attempting to create buttons that can add or remove CSS classes. I found a helpful tutorial on this topic at http://www.w3schools.com/jquery/jquery_css_classes.asp

Unfortunately, my code doesn't seem to be working as expected. Here is the script in the head section:

<script>
 $(document).ready(function(){
 $("button#31").click(function(){
 $(".Page1").addClass("georgia nite");
 });
 });
</script>

<script>
 $(document).ready(function(){
 $("button#32").click(function(){
 $(".Page1").toggleClass("georgia nite");
 });
 });
</script>

<style>
 .georgia { font-family: Georgia; }
 .nite { background: #000; color: #fff; }
</style>

(The "Page1" represents the name of a class assigned to a div...)

<div id="page-content-wrapper" class="Page1">

Below is the code within my body section...

<button id="btn31">Add Class</button>
<button id="btn32">Toggle</button>

In addition, I've included the new styles ("georgia" and "nite") in my style sheet for good measure. However, when I click the "Add Class" or "Toggle" buttons, nothing happens. Can anyone point out what might be incorrect in my approach?

Answer №1

The identifiers in your HTML file do not match the ones in your JavaScript code.

To correctly target identifiers, use a # followed by the value of the id attribute. For example, use $("#btn32") for <button id="btn32">.

Updated JavaScript code with corrected identifier selector from button#32 to #btn32:

$(document).ready(function(){
   $("#btn32").click(function() {
   $(".Page1").toggleClass("georgia nite");
 });

Answer №2

Have you ever tried adding multiple classes separated by spaces? This code snippet functions perfectly for me with just one class:

$('#cl_wind').click(function() {
    $('#_error').addClass('hidden');
});

Here is the HTML portion:

<div id="_error">Some text</div>
<button id="cl_wind"></button>

Update: It was pointed out that the element's ID used in your JavaScript code should match the actual ID of the element. The ID must be a single identifier and cannot be split into characters or numbers.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jQuery animation that smoothly fades out from the left and fades in from the right

This survey is designed to assist individuals in determining where they should go with a specific type of ticket. Currently, everything is functioning smoothly, but I would like to add a sleek animation to each ul transition. Whenever a button is clicked ...

jQuery event handlers

I'm looking for some guidance on how to reattach a click event after detaching it in the following code: $("button").click(function(){ $("button").off('click'); //detach click for the button below } Below, you'll find a button in ...

Is there a way to adjust the placement of text in an HTML document?

Just starting out with web development and created some HTML code: <html> <body> {errors} <p>Input your numbers:</p> <form method="post" action="."> <p><inpu ...

What is the correct way to reference this data element in Ajax?

I am attempting to retrieve the elevation data for 732 meters from the JSON API response below: {"results":1,"data":[{"wind":{"degrees":200,"speed_kts":6,"speed_mph":7,"speed_mps":3,&quo ...

What is the method to conceal a certain element in jQuery based on the value of another element?

I am dealing with the following HTML structure: <button id="hideToggle">show/hide</button> <form id="item"> <div>Item 1 <input name="item1" type="number"/></div> <div>Item 2 <input name="item2" type="nu ...

The PHP on server could not be loaded by Ajax

Trying to establish a PHP connection, encountering an error and seeking assistance. The error message displayed is as follows: { "readyState": 0, "status": 0, "statusText": "NetworkError: Failed to execute 'send' on 'XMLHttpReq ...

Establish a hyperlink using the jQuery class

Can you use JQuery to turn the text "Link" into a hyperlink in the following code? <p>Hello World! <span class="link">Link</span>.</p> ...

Can you explain the process of NuxtJS css extraction for creating static websites?

I am currently working on creating a static website using my minimal code with Nuxt. This code includes integration of the tailwindcss toolkit and vue2-leaflet. When I run nuxt generate I end up with two CSS files - one for the tailwindcss styles and an ...

Undefined variable options

I am currently working on my first plugin and facing some challenges. In my code, I have defined two global variables: defaults and options. Following the plugin pattern, my code looks like this: (function ( $ ) { var defaults; var options; $.f ...

Having Trouble Scooting Down the Page on Mobile?

Hello there! I'm having a bit of trouble trying to figure out why the scrolling functionality isn't working on my small web app when it reaches the media breakpoint for mobile devices. If you'd like to take a look, here's the link to ...

Limiting jQuery datepicker to only show the selected date and disabling all others

I have two datepickers named startdate and enddate. My goal is to restrict all other dates in the enddate datepicker except the selected date from the startdate datepicker. For instance, if I choose 15/12/2016 from the startdate datepicker, I only want the ...

What is the best way to align two round buttons on each line with a single button centered above them, all without any spacing between the buttons below, and vice versa

https://i.sstatic.net/oOwY6.png Is it possible to align the buttons on the left side like they appear on the right? Each group should have padding and display with flow-root. .group { display: flow-root; padding: 7px 0px 7px 0px; } button.a { ...

When viewing HTML "Div" on smaller screens, the full height may not be displayed properly

My setup includes two monitors: one is 24" and the other is my laptop's 12.5" screen. I have a red box (div) in my web application that displays full height on the larger monitor, but only partially on the smaller one. I'm puzzled as to why it s ...

Blending PHP with jQuery

I'm currently working on the same page as before but this time, I'm using it to experiment with jQuery. I'm trying to learn it for my 'boss', but unfortunately, I can't seem to get the JavaScript in this file to run at all, le ...

Transforming JavaScript controls into jQuery

I have been working on implementing touch controls for a JavaScript game, and I came across a solution that seemed promising. It involved using jQuery, but I needed to convert it to pure JavaScript to make it compatible with my game. The original code in ...

Activating the onclick function to open a tab and automatically position the cursor inside a textfield

I have a requirement to automatically place the cursor on a specific field whenever a rich tab is navigated to. I attempted using onclick and onlabelclick on the richTab, but it did not work as expected. Then, I tried utilizing ontabenter, which called my ...

Clicking on buttons in the header does not lead to the intended section when scrolling

I have just completed a website project for a Udemy course, following all the instructions provided. However, I am facing an issue with the functionality of two buttons on my site. I want these buttons to scroll to specific sections when clicked. The "I&ap ...

Animate a jumping figure using jQuery

Is it possible to create an animation of a person jumping from the bottom of the screen to the top, with the scroll bar following them? I have my doubts but would love to know if it can be done. If you want to see what I mean, check out this PDF: http:// ...

When using the post method in jQuery, it may send data that is unspecified in the request body

Greetings to everyone and I hope you have a fantastic start to the new year. I've been attempting to operate an API on localhost that will store input data in MongoDB. The issue arises when attempting to send data using the post method. The request ...

Utilizing multiple class names in Material UI with identical definitions

When working with traditional CSS, it is common to define shared properties between classes like this: .classA,.classB{ background-color: black; } In Material UI and using theming, the equivalent would be: styles = (theme)=>({ classA:{ ba ...