user557108
user557108

Reputation: 1215

Swap DOM Elements without Losing New Lines

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.

Upvotes: 2

Views: 41

Answers (2)

dfsq
dfsq

Reputation: 193301

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.

Upvotes: 0

Parth Raval
Parth Raval

Reputation: 4453

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

Upvotes: 1

Related Questions