What the best way to switch two elements in DOM with jquery?
<div id="switchme2">some other elements in here....</div>
<div class="some other elements"></div>
<div id="switchme1">some other elements in here....</div>
should end in:
<div id="switchme1">some other elements in here....</div>
<div class="some other elements"></div>
<div id="switchme2">some other elements in here....</div>
You’ll get people telling you to use jQuery’s
before,after, and such, but beware, that can mess things up if there are text nodes on either side of either element (more on that below).Because of that (and for people not using jQuery), you can just use the DOM directly:
Note that it’s fine if the reference element (
next1ornext2above) isnull;insertBeforehandles that correctly (by adding at the end of the parent, likeappendChildwould).Usage combined with jQuery:
Live example:
More about jQuery’s
before,after, and such: Because jQuery tends to give you access mostly to elements (which is what you want 95% of the time!), if the elements you want to swap have text nodes around them, using those methods will mess things up. (You also have to either remember which one goes in front or figure it out.) In contrast, theswapElementsmethod above above works regardless of whether the elements are surrounded by other elements or text nodes, and you don’t have to remember or figure out which should go in front.