AnswerBun.com

Jquery Select all IDs in different Sections

Stack Overflow Asked by abcid d on December 23, 2020

I have 2 same IDs inside 2 different sections. When the button is clicked, I want it selects the id inside this section and apply a style, then it will select the id in a different section and apply that style, as well.

My sample below just works inside the first section. Please give a hand.

$( 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>

One Answer

The same ID should only be once per page. If you have multiple the DOM only attaches the attributes to the first ID thats found with that name.

$( 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>

Answered by MPortman on December 23, 2020

Add your own answers!

Related Questions

Laravel Slow queries

5  Asked on November 7, 2021 by squiggs

     

Display image that returns HTTP 503 in Firefox

2  Asked on November 7, 2021 by brainstone

       

Simple TCP listener on swift

1  Asked on November 7, 2021 by mr-park

       

check the type of the only child in react

1  Asked on November 7, 2021

 

Cannot update document using the NodeJS MongoDB driver

1  Asked on November 7, 2021 by niaz-m-sameer

   

Can not convert umlauts (Ü Ö Ä ü ö ä è é) to .utf8

2  Asked on November 7, 2021 by salome-tsiramua

       

elegant way of extracting option value when need it

1  Asked on November 7, 2021 by user804968

 

Sign PDF asynchronous using PDFBox

0  Asked on November 7, 2021 by lawrence-leung

         

Get non hidden element with previousElementSibling

2  Asked on November 7, 2021 by jens-trnell

     

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP