-1

If I want to replace many times an element with an id like this :

$("#anIdElement").replacewith("#anotherIdElement");

This shouldn't work, so my question is : What can be used to replace many times a specific element with another another.

Example :

 <table>
    <tr>
        <td id="theFirsttd">Original content</td>
    </tr>
    <tr>
        <td id="atd">Replace the current content by the original</td>
    </tr>
    <tr>
        <td id="atd">Replace the current content by the original</td>
    </tr>
 </table>

The problem here is that I can't replace the element with the id named atd, I can only once. Am I right ? So, is it possible to use something like remove() then append() to get it ?

Cido
  • 13
  • 3
  • 3
    The problem doesn't exist because ids have to be unique, hence there is always only one element with a specific id ;) – Andreas Mar 05 '19 at 16:20
  • Yes I tried to clone but it didn't give me the same id and the cells are generated with an id – Cido Mar 05 '19 at 16:21
  • consider using `document.getElementByClassNames()` of javascript which will store the divs in an array. – YourPalNurav Mar 05 '19 at 16:24
  • 1
    Fix it at the source, ie. where the HTML is generated. Any attempt to fix this in JS is a hack and not addressing the underlying issue – Rory McCrossan Mar 05 '19 at 16:25

3 Answers3

1

You can put all id's you want to change in array and loop on it

var array = ['theFirsttd', 'atd']

for (var item of array) {
 $(`#${item}`).attr("id", "newId");
}

watch out if you have same id name on severals elements (which is not supposed to happens as Id shoud be unique.

Hope it will help

CosmOrtome
  • 175
  • 1
  • 11
0

Well, first, you're HTML is invalid because two objects share the same id - this could be solved by making those classes instead. Second, assuming that you are just copying the content of the one object to another object, using jQuery, you could do something like :

$('.atd').html( $('#theFirsttd').html() );
do or do not
  • 146
  • 1
  • 5
0

In jQuery you can do with these code, but first you must fix the html in your example:

<table>
   <tr>
       <td id="theFirsttd">Original content</td>
   </tr>
   <tr>
       <td class="atd">Replace the current content by the original</td>
   </tr>
   <tr>
       <td class="atd">Replace the current content by the original</td>
   </tr>
</table>

<script>
// reemplace all the items (jQuery)

$(function(){ // <- wait for the DOM
  var $first = $('#theFirsttd');
  $('.atd').each(function{ // <- eval each element with atd class selector
    $(this).replaceWith($first.clone()) // <- replace each one with first td clone
  });
});
</script>
MR0
  • 164
  • 7