Choose all of the IDs from various sections using Jquery

I am facing an issue with having 2 identical IDs inside 2 separate sections. When the button is clicked, I want it to select the ID within this section and apply a style, then also select the ID in the other section and apply that same style.

The code snippet provided below only works for the first section. Can someone please help me out?

$( document ).ready(function() {
    $('#clickMe').click(function() {
      $('#square').css('background-color', 'red');
    })
});
.block {width: 100%; padding-bottom: 40px;}
#square {width: 80px; height: 30px; border: 1px solid gray}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="block">
  This is block 1
  <button id="clickMe">Click Me</button>
  <div id="square"></div>
</div>
<div class="block">
  This is block 2
  <div id="square"></div>
</div>

Answer №1

It is important to ensure that each ID is unique on a page to avoid conflicts. If the same ID is used multiple times, the DOM will only recognize and apply attributes to the first instance it finds.

$( document ).ready(function() {
    $('#clickMe').click(function() {
      $('.square').css('background-color', 'red');
    })
});
.block {width: 100%; padding-bottom: 40px;}
.square {width: 80px; height: 30px; border: 1px solid gray}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="block">
  This is block 1
  <button id="clickMe">Click Me</button>
  <div class="square"></div>
</div>
<div class="block">
  This is block 2
  <div class="square"></div>
</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

Using JQuery functions from other JavaScript files is Simple

When it comes to my CSS, I have taken the approach of creating smaller files for specific functions and then using minification to merge and compress them into one file for easier download. I want to apply the same strategy to my JS Files by logically sep ...

The appearance of Google Font CSS may vary when retrieved using WGET

Uncovering an issue while attempting to dynamically fetch a Google Fonts css file to extract the font URL. The scenario looks like this: (Viewed in Chrome) Contrast that with: WGET -qO- http://fonts.googleapis.com/css?family=Droid+Sans Upon inspecti ...

Create a sleek transition for your Bootstrap 4 fixed Navbar by having it smoothly slide down and change to a

Throughout my experience with HTML/CSS, I have predominantly relied on themes that included this feature by default. However, as I now venture into building from scratch, I find myself struggling to recreate it. You'll notice that I have a stylish fi ...

What is the proper syntax for using .focus() with the nextElementSibling method in typing?

As I strive to programmatically shift focus in my form using nextElementSibling, I encounter a challenge with typing variables/constants due to working with Typescript... I have managed to achieve success without typing by implementing the following: myF ...

Tips for adjusting column positions in a table while maintaining a fixed header and utilizing both horizontal and vertical scrolling

Is there a way to display a table that scrolls both horizontally and vertically, with the header moving horizontally but not vertically while the body moves in both directions? I have been able to shift the position of the columns, however, I am struggling ...

Utilize Node JS to assign variables to HTML form inputs

Can anyone help me with storing HTML form inputs in variables using Node JS? I'm having trouble getting it to work properly. Below is the HTML form snippet: <form action="localhost:8080/api/aa" method="post"> <input id="host" type="text ...

Using JAVA to generate SVG images, then embedding them into HTML using Base64 encoding URI

I am currently developing a service to generate SVG images. The main criteria is that the generated SVG must be compatible with an img tag (with the added bonus of working in a script tag) and it needs to function without the use of JavaScript. After some ...

Navigating through a URL to grab a specific JSON object: a step-by-step guide

When I receive a json from a URL containing numerous objects, how can I extract only the slugs provided in the json below? I am open to solutions using either PHP or JavaScript. On one hand, I need to understand how to specifically retrieve the desired ob ...

I am looking to create a div that can consistently refresh on its own without needing to refresh

I have implemented a comment system using ajax that is functioning well. I am looking to incorporate an ajax/js code to automatically refresh my "time ago" div every 5 seconds so that the time updates while users are viewing the same post. Important note: ...

Even after being removed from the DOM using Ajax load, JQuery continues to execute

Currently, within my Laravel 5.2 single page application development, I am faced with the following issue. I have an add.blade.php file and an edit.blade.php file, both containing a script with the same class name and id. When I use .load to load add.blade ...

What causes the off-canvas menu to displace my fixed div when it is opened?

Using the Pushy off-canvas menu from GitHub for my website has been great, but it's causing some trouble with my fixed header. When I scroll down the page, the header sticks perfectly to the top, but once I open the off-canvas menu, the header disappe ...

Detecting single letters in a sentence and changing their appearance using CSS

Looking to make a subtle change to text? I need to swap out single letters in a passage (I have a cat that ate a fish). Any ideas on how to do this? The goal is to input a block of text into a textbox, then display it in a div. I've had difficulty fi ...

Is it true that setting the background size to cover does not actually stretch the image?

Hi, I seem to be having trouble stretching an image using the background-size property. Despite setting it to cover, one or two sides of the image are always getting cropped. What I really want is a way to distort the image so that it stretches to fit any ...

Formatting dates with JQuery

Can someone help me with validating a date field in "mm-dd-yyyy" format using the jQuery validation plugin? I want to show the message "Please enter date in mm-dd-yyyy" if the format is violated. How can I achieve this? Appreciate any assistance, thank yo ...

Link Google Map Marker Click Event with Dynamic Binding

I'm currently working on binding a click event to a link that is positioned outside the Google Map Canvas. The goal is to open an "infowindow" on a map marker when this link is clicked. While I know how to achieve this for a specific point, I need a d ...

Next.js - Anticipated that the server HTML would include a corresponding <div> within <div> tag

For a live demonstration, please click here In my current project, I am experimenting with creating a simple layout that adjusts based on the user's screen size. Specifically, on mobile devices, only the latest posts should be displayed. On desktops, ...

The adhesive navigation bar isn't adhering

I'm having issues with making my navbar inside a header sticky over the whole page. Despite trying various solutions like removing overflow, adjusting the flexbox, and setting a specific height on the parent element, I still can't get it to work. ...

Minor Chrome compatibility problems with CSS alignment

As someone who is new to stackoverflow, I've always found it to be a valuable resource for answers. I've had success building HTML 5 banner ads using GSAP (Greensock Animation Platform) in the past, but now I'm facing a CSS alignment issue t ...

Retrieving information from a JSON web service can easily be done using just JavaScript and jQuery

I recently downloaded a sample application from the following URL: . I am pleased to report that the part I have implemented is functioning flawlessly: <script src="scripts/jquery-1.3.2.debug.js" type="text/javascript"></script> <script src ...

Creating a customized ASP.NET AJAX control that utilizes templating for dynamically showing or hiding items within a placeholder

I am dealing with a custom templated control (toolbar) that includes a custom user control (button). The button utilizes jQuery for styling and managing various states, postbacks, and non-postbacks. Within this setup, some of the buttons are initially hid ...