jQuery id selector issue: not selecting elements properly

It seems like I am overlooking a very fundamental aspect here.

Essentially, there are 2 div elements in the HTML markup. When one is clicked (#x), the other div element (#block1) gains a new class (.change), resulting in a change in its color.

The issue lies within the selector ("#block1") used inside the click function. Substituting the id of the first div with a class works perfectly fine. However, using an id instead renders it invalid.

$(document).ready(function() {
  $("#x").click(function() {
    $("#block1").toggleClass("change");
  });
});
#block1 {
  width: 20vw;
  height: 20vw;
  background: gold;
  margin-left: auto;
  margin-right: auto;
  position: relative;
}

#x {
  height: 5vw;
  width: 5vw;
  background: #333;
  position: relative;
  right: -60vw;
  top: -15vw;
  cursor: pointer;
}

.change {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div id="block1"></div>
<div id="x"></div>

Answer №1

If you want to override the background color specified in #block1, make sure to include #block1 along with your .change declaration. Hopefully, this is the solution you were searching for.

   $("#x").click(function(){
     $("#block1").toggleClass("change");
   });
#block1{
  width: 20vw;
  height:20vw;
  background:gold;
  margin-left: auto;
  margin-right: auto;
  position: relative;
}

#x{
  height: 5vw;
  width: 5vw;
  background: #333;
  position: relative;
  right: -60vw;
  top: -15vw;
  cursor: pointer;
    }

#block1.change {
  background: red;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="block1">
   </div>

   <div id ="x">
   </div>

Answer №2

The background color set in #block1 cannot be overridden by your CSS class, .change, due to style precedence.

To make it work in this case, you need to be more specific.

Instead of:

.change {
    background: red;
}

You should use:

#block1.change {
    background: red;
}

Answer №3

To ensure your CSS overrides the gold color, make sure to include the !important declaration:

.change {
  background: red !important;
}

Your updated code should look like this:

$(document).ready(function() {
  $("#x").click(function() {
    $("#block1").toggleClass("change");
  });
});
#block1 {
  width: 20vw;
  height: 20vw;
  background: gold;
  margin-left: auto;
  margin-right: auto;
  position: relative;
}

#x {
  height: 5vw;
  width: 5vw;
  background: #333;
  position: relative;
  right: -60vw;
  top: -15vw;
  cursor: pointer;
}

.change {
  background: red !important;
}
<body>
  <div id="block1">
  </div>

  <div id="x">
  </div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">


  </script>
</body>

Answer №4

$(document).ready(function(){
   $("#x").click(function(){
     $("#block1").toggleClass("change");
   });
});
 

#block1{
  width: 20vw;
  height:20vw;
  background:gold;
  margin-left: auto;
  margin-right: auto;
  position: relative;
}

#x{
  height: 5vw;
  width: 5vw;
  background: #333;
  position: relative;
  right: -60vw;
  top: -15vw;
  cursor: pointer;
    }

#block1.change {
  background: red;
  }
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="block1">
   </div>

   <div id ="x">
   </div>

The styling for #block1 takes precedence and overrides the style of the .change class. Update your CSS to this:

 #block1.change {
     background: red;
    }

For more information on CSS specificity, visit https://developer.mozilla.org/en/docs/Web/CSS/Specificity

Answer №5

Feel free to utilize this code and be sure to carefully study the CSS properties.

<!DOCTYPE html>
<html>
<head>
  <title>ok</title>
  <script type="text/javascript" src="jquery.js"></script>
<style type="text/css">
#block1{
  width: 20vw;
  height:20vw;
  background:gold;
  margin-left: auto;
  margin-right: auto;
  position: relative;
}

#x{
  height: 5vw;
  width: 5vw;
  background: #333;
  position: relative;

    }

#block1.change {
  background: red;
  }
</style>

</head>
<body>
<div id="x">
  asa
</div>
<div id="block1">
  aasds
</div>
<script type="text/javascript">
  $( document ).ready(function() {

    $( "#x").click(function() {

        $("#block1").toggleClass("change");

    });

});
</script>

</body>
</html>

Answer №6

It is not advisable to add a red background to the specific id selector #block1.change. If you intend to apply the change class to multiple elements, it would be better to override the background property in the .change class using !important (since the css #block1 already has a background:gold) like so:

.change {
    background: red !important;
}

Snippet,

$(function() {
  $("#x").click(function() {
    $("#block1").toggleClass("change");
  });
});
#block1 {
  width: 20vw;
  height: 20vw;
  background: gold;
  margin-left: auto;
  margin-right: auto;
  position: relative;
}

#x {
  height: 5vw;
  width: 5vw;
  background: #333;
  position: relative;
  right: -60vw;
  top: -15vw;
  cursor: pointer;
}

.change {
  background: red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="block1">
</div>

<div id="x">
</div>

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

Make dark mode the default setting in your Next JS application

In my Next JS application, I have implemented both isDarkMode and handleDarkMode functions. Within the Header component, there is a toggle button that allows users to switch between light and dark modes. <ThemeContainer> <label classN ...

Enhancing this testimonial slider with captivating animations

I have designed a testimonial slider with CSS3 and now I am looking to enhance it by adding some animation using Jquery. However, I am not sure how to integrate Jquery with this slider or which plugins would work best for this purpose. Can anyone provide g ...

Input field with JQuery datepicker showing only months and years

I have encountered a question that closely resembles the one discussed here: year/month only datepicker inline The scenario I'm facing involves utilizing the input version instead of the div. In the case of using the div, the ui-datepicker-calendar ...

Loading options dynamically in a dropdown list using KnockoutJS

I am new to KnockoutJS and I have successfully worked with static data in dropdown lists. Now, I need to dynamically populate the dropdown list from a controller. 1. I want to retrieve a dynamic list from my controller and populate it in a dropdown list. ...

Manipulate the value of the <input> element when focused through JavaScript

After I focus on the input field, I was expecting to see Bond-Patterson, but instead, I am only getting Bond. What could be causing this discrepancy and how can it be fixed? $('input[name="surname"]').attr("onfocus", "this.placeholder='Bo ...

The padding on this button seems to be arbitrary and nonsensical

I attempted to create a button with a red border that is positioned at the bottom and center, but the padding seems to be interfering with my design. It appears that with the border, the width extends to 100% which doesn't make sense. I have tried va ...

How to insert space after every item generated by ng-repeat in AngularJS

I'm looking to evenly distribute elements based on this inquiry How to distribute li elements equally? I am utilizing angular with jade: ul li(ng-repeat="item in items") {{item.name}} However, ng-repeat does not create newlines after each element ...

Error message: Injector Error: R3InjectorError(Standalone[_AppComponent])[_WebService -> _WebService -> _WebService] occurred

Being a student, I must apologize in advance for any mistakes in terminology or gaps in my understanding. I am currently developing an Angular front-end to communicate with my backend API. However, I keep encountering the following error in the web page c ...

Tips on extracting code differences from code inspector

Utilizing the Chrome code inspector is extremely valuable, but I often find it challenging to track the modifications made to CSS and HTML live. This becomes particularly cumbersome when there are multiple tags being modified. Are there any Chromium exten ...

Achieve the effect of making the Bootstrap JS Collapse text bold after it has been

Is there a way to make Bootstrap JS Collapse text Bold after it has been clicked on? <tr data-toggle="collapse" data-target="#demo8" class="accordion-toggle"> <td> <div class="fa ...

Material design for Angular applications - Angular Material is

Recently, I decided to explore the world of Angular and its accompanying libraries - angular-material, angular-aria, and angular-animate. I'm eager to experiment with this new styling technique, but it seems like I've hit a roadblock right at the ...

How can I use jQuery to add styling to my menu options?

Looking to customize my menu items: <ul> <li class="static"> <a class="static menu-item" href="/mySites/AboutUs">About Us</a> </li> <li class="static"> <a class="static-menu-item" href="/m ...

The Bootstrap carousel comes with a brilliant feature! Conceal those 'previous' and 'next' buttons when you reach the first and last slide. However, it seems like the 'slide' event is not functioning as

I have implemented a standard Bootstrap carousel on my website: <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data- ...

Utilizing custom links for AJAX to showcase targeted pages: a beginner's guide

I am putting the final touches on my website and realized that it may be difficult to promote specific sections of the site because the browser address never changes. When visitors click on links, they open in a div using Ajax coding. However, if I want to ...

Expand the div width to the specified measurement horizontally

Is there a way to horizontally collapse a div (container) to a specific width that I can adjust, effectively hiding its content? The collapse effect should move towards the left. <div id="container"> <button type="button" id="myButton"> ...

Spinning html/css content using JavaScript

Greetings! I am currently working on a demo site using just HTML, CSS, and JavaScript. Typically, I would use Ruby and render partials to handle this issue, but I wanted to challenge myself with JavaScript practice. So far, I have created a code block that ...

Tips for Utilizing PHP Without the Need to Refresh the Page

Below are the contents of three files with their respective code: Controler.php <iframe id="frame1" style="display:none"></iframe> <iframe id="frame2" style="display:none"></iframe> <button onClick="document.getElementById(&apo ...

What could be the reason for scrapy not returning any URLs?

Recently, I attempted to develop a tool to simplify my apartment search and access relevant information quickly (the website is not very user-friendly). However, I have encountered an issue and I may be overlooking something obvious...or perhaps I'm j ...

How can you make a dropdown button interactive and display a list simultaneously?

I'm facing an issue with lines 45-47 in the second link. If that code is present, the button animates when clicked (which is great) BUT the dropdown items ("About," "Archive," "Contact") do not appear. If I remove lines 45-47, the dropdown items appea ...

Jquery script that utilizes the Steam WebAPI to return data

I'm encountering an issue with a script I found on github. I added value.appid myself, thinking it was logical, but I believe that data.response.games contains values for all my games. How can I either print or view what is defined? I would like to ...