i want replace a button in a website
how select a element before a element?
better solution then
$('.col')[2]
<div class="row">
<div class="col">
<button id="itemCaptureResultLeftButton" class="bt"><</button>
</div>
<div class="col">
<div class="row">
</div>
<div class="row">
</div>
</div>
<div class="col">
<button id="itemCaptureResultRightButton" class="btn">></button>
</div>
</div>
my code
var itemCaptureResultRightButtonSW = document.createElement("button");
itemCaptureResultRightButtonSW.setAttribute('id', 'itemCaptureResultRightButtonSW');
itemCaptureResultRightButtonSW.innerHTML = '>';
itemCaptureResultRightButtonSW.className += "btn";
document.getElementById('itemCaptureResultRightButton').append(itemCaptureResultRightButtonSW);
//$('#itemCaptureResultRightButton').remove();
i expected
<button id="itemCaptureResultRightButton" class="btn">></button>
<button id="itemCaptureResultRightButtonSW" class="btn">></button>
i got
<button id="itemCaptureResultRightButton" class="btn">>
<button id="itemCaptureResultRightButtonSW" class="btn">></button></button>
2
Answers
The problem is that you want to append as a sibling of the previous button but you are appending it as a child, therefore you have this behaviour.
You can use insertBefore:
You can also use parentNode to get access to the parent node and then append as a child:
And then you could remove the previous one as I understand you want.
Instead of using
append()
the way you did it, which will add the new button as a child of the existing button, you should usereplaceWith()
to replace the existing button with the new button directly:I noticed you want to replace the original button with a new button that only has a different
id
.A simpler way to achieve the change you wanted is to use directly change the
id
attribute of the original button by usingsetAttribute()
: