Tell me why it does not work, I have on page 2 id with a value for example test. The following code changes only the first value of the block, why, how to change 2 at once?

$('#test').text(deliveryCost); 
  • one
    ID can be only one on the page! More precisely in one area. - user207618
  • use different id, or use class - soledar10
  • Alas, even google is lobbying for a standard with a unique ID - it started issuing errors in the console. Therefore, it is better from sin, not to duplicate the ID. Nevertheless, in practice it is difficult - for example, the customer wanted to display several existing forms (which were previously on their pages) - on one page: programmers do not like to spend their time on labud, if everything works and so :) - Alexander Goncharov

1 answer 1

The selector on id issues only the first element found.

It is not recommended to use elements with identical id, but if you really really want, then there is such a hack: use Attribute Equals selector instead of id selector.

 $('button').on('click',magic); function magic(){ $('[id="test"]').text('clicked!!!'); } 
 .test1{ color:blue; } .test2{ color:violet; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='test' class='test1'>test1</div> <div id='test' class='test2'>test2</div> <button>Магия</button>