2

I am not able to swap DOM elements and preserve the space/new line(s) between them.

<div id="buttons">
    <button id="button-a">Button A</button>
    <button id="button-b">Button B</button>
</div>

<script>
    let buttons = document.querySelector('#buttons');
    let buttonA = document.querySelector('#button-a');
    let buttonB = document.querySelector('#button-b');

    buttons.insertBefore(buttonB, buttonA);

    setTimeout(function () {
        buttons.insertBefore(buttonA, buttonB);
    }, 1000);
</script>

enter image description here enter image description here

NOTE: The buttons can have 0 to N new lines after them.

user557108
  • 1,195
  • 3
  • 17
  • 26
  • I just tested your code and it seems to run fine. The only thing that happens is that the first button will become a little bigger because the width of the letter **B** in **Button B** is smaller than the letter **A**. – obscure Apr 30 '19 at 11:10

2 Answers2

1

$.fn.swap = function (el) {
  el = el.jquery ? el : $(el);
  return this.each(function () {
  $(document.createTextNode('')).insertBefore(this).before(el.before(this)).remove();
  });
};
$('input').click(function () {
  $('.one').swap('.two');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" value="click" />
<div id="buttons">
  <button class="one" id="button-a">A</button>
  <button class="two" id="button-b">B</button>
</div>
Parth Raval
  • 4,097
  • 3
  • 23
  • 36
0

This is expected behaviour due to how white-space character interpreted by browser. In your case initial button layout has some white space characters, looks new lines. Browser is going to represent then all (new lines, tabs, spaces) as single white space. This is why you see some initial space between buttons.

After you change buttons position in DOM, you effectively get rid of those white spaces. Hence buttons visually touch each other.

Simple solution is either to preserve white space between buttons:

buttons.insertBefore(buttonA, buttonB);
buttons.insertBefore(document.createTextNode(' '), buttonB)

Or you could make sure your buttons enforce proper CSS margines so that white space chars are neglected or don't exist all. See this question.

dfsq
  • 191,768
  • 25
  • 236
  • 258