How to swap HTML elements in javascript?

javascript replace html element
replacechild javascript
insertbefore javascript
javascript insert html after element
javascript replace all child nodes
javascript swap div content
jquery swap elements
javascript move element in dom

I am using classic Javascript for DOM scripting, i have a set of DIV's in a container DIV. On click event of child DIV's, i want that the child DIV which has caused event to be swaped with the DIV above it.. my code goes here..

 <div id="container">
        <div onclick="swapDiv(event);">1</div>
        <div onclick="swapDiv(event);">2</div>
        <div onclick="swapDiv(event);">3</div>
 </div>

if DIV 2 has been clicked it should be swap with DIV 1

This code will do what you want (if you want to swap the selected with the first child element). In case you want something else you need to be more precise.

<script type="text/javascript">

function swapDiv(event,elem){
    elem.parentNode.insertBefore(elem,elem.parentNode.firstChild);
}

</script>


 <div id="container">
        <div onclick="swapDiv(event,this);">1</div>
        <div onclick="swapDiv(event,this);">2</div>
        <div onclick="swapDiv(event,this);">3</div>
 </div>

How to swap HTML elements in javascript?, This code will do what you want (if you want to swap the selected with the first child element). In case you want something else you need to be  One of the options for configuring the HTML tags on a page is to grab all the tags of a certain type and format them as part of a loop. That’s what the following example does. In this case, the example uses getElementsByTagName() to obtain an array of all of the elements of a particular type on a page.

An element's parentNode property gives you its parent node. Elements have an insertBefore function that inserts an element before another reference element (moving it if it's already elsewhere in the tree). And nodes have a previousSibling that gives you the previous sibling node (which may or may not be an element). So:

function swapDiv(elm) {
    var previous = findPrevious(elm);
    if (previous) {
        elm.parentNode.insertBefore(elm, previous);
    }
}

...where findPrevious looks like this:

function findPrevious(elm) {
   do {
       elm = elm.previousSibling;
   } while (elm && elm.nodeType != 1);
   return elm;
}

...where your onclick attributes should be:

onclick="swapDiv(this);"

...although you may want to look into DOM2 event hooking instead (addEventListener, or attachEvent on IE).

Slightly OT, but can I recommend using any of the several libraries available that make your life easier, such as Prototype, jQuery, Closure, or any of several others. In fact, there was an error in an earlier version of this because it had been that long since I'd dealt with the DOM directly. :-)

Swap two html elements and preserve event listeners on them , Swap two html elements and preserve event listeners on them · javascript jquery dom dom-events. There are similar questions, but all the  The easiest way to modify the content of an HTML element is by using the innerHTML property. To change the content of an HTML element, use this syntax: document.getElementById( id ).innerHTML = new HTML

From the sounds of it you basically just want to swap the div with the div before it, ergo with the previousSibling. You could maybe look at doing an insertBefore but instead of creating a new element use the existing one. I'm not sure what happens to the attached events tho, if they will be copied over correctly.

HTML DOM replaceChild Method, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java  By using JavaScript, you can change any part of an HTML document in response to input from the person browsing the page. Before you get started, take a look at a couple of concepts. The first is a method called getElementById. A method is an action that’s done to or by an object in a JavaScript program.

In principle you just insertBefore your clicked element before its previous element sibling. However, the presence of whitespace Text nodes makes that more annoying than it should be in traditional scripting. The Element Traversal API will make this easier, but until it is more widely supported in browsers, helper functions are necessary, eg.:

<div id="container">
    <div>1</div>
    <div>2</div>
    <div>3</div>
</div>

<script type="text/javascript">
    // Bind event to each line div
    //
    var div= firstElementChild(document.getElementById('container'));
    while (div!==null) {
        div.onclick= swapWithPreviousElement;
        div= nextElementSibling(div);
    }

    // Move element before its previous element sibling
    //
    function swapWithPreviousElement() {
        var previous= previousElementSibling(this);
        if (previous!==null)
            this.parentNode.insertBefore(this, previous);
    }


    // We've used some Element Traversal API methods but some
    // browsers don't support them yet. Provide wrapper functions
    // for compatibility.
    //
    function previousElementSibling(element) {
        if ('previousElementSibling' in element)
            return element.previousElementSibling;
        do
            element= element.previousSibling;
        while (element!==null && element.nodeType!==1);
        return element;
    }
    function nextElementSibling(element) {
        if ('nextElementSibling' in element)
            return element.nextElementSibling;
        do
            element= element.nextSibling;
        while (element!==null && element.nodeType!==1);
        return element;
    }
    function firstElementChild(element) {
        if ('firstElementChild' in element)
            return element.firstElementChild;
        var child= element.firstChild;
        while (child!==null && child.nodeType!==1)
            child= child.nextSibling;
        return child;
    }
</script>

How To Toggle Text, Learn how to toggle text with JavaScript. Toggle Text. Hello. Toggle Text of an Element. Step 1) Add HTML: Example. Is there any simpler way to swap two elements in an array? You only need one temporary variable. Edit hijacking top answer 10 years later with a lot of ES6 adoption under our belts: Given the array arr = [1,2,3,4], you can swap values in one line now like so: This would produce the array [2,1,3,4]. This is destructuring assignment.

This works for siblings, should work for any two nodes:

function swapElements(el1, el2) {
    let prev1 = el1.previousSibling;
    let prev2 = el2.previousSibling;

    prev1.after(el2);
    prev2.after(el1);
}

swapNode method JavaScript, Reference to the element to swap with. Return value: Returns a reference to the current element. Example HTML code 1:. Note that the swap cannot be a simple three step swap. Each of the two elements need to be removed from the dom first because they may have siblings that would need updating, etc. Solution: I put in two holder div's to hold the place of each node to keep relative sibling order.

Switching the position of two divs - JavaScript, <script type="text/javascript"> jQuery(document).ready(function() { div1 If you are simply swapping two elements around then you would be  Often, with JavaScript, you want to manipulate HTML elements. To do so, you have to find the elements first. There are several ways to do this: Finding HTML elements by id. Finding HTML elements by tag name. Finding HTML elements by class name.

jQuery: swap - JSFiddle, Test your JavaScript, CSS, HTML or CoffeeScript online with JSFiddle code editor. Swap an element with another one. 3. * @author: Yannick Guinness. 4. Using Events. The HTML DOM allows you to execute code when an event occurs. Events are generated by the browser when "things happen" to HTML elements: An element is clicked on. The page has loaded. Input fields are changed.

Swap HTML elements randomly using Javascript, Swap HTML elements randomly using Javascript. Posted by Niklas on January 7, 2011 Leave a comment (0) Go to comments. I once need to swap a bunch of P  Despite their importance in the JavaScript world, there is a lot of things they don't support out of the box. For example, you can't swap two items in an array using the built-in Array methods: I know, right? In this short article, I will show you how to easily swap items in an array. Onwards! General Approach for Swapping

Comments
  • And if div 1 is clicked?
  • if div is 1 then no swapping...
  • swap just the contents, or the entire elements?
  • if you ever fancy using jQuery: .replaceWith()
  • Yeah that's about the same as what I thought, but he doesn't always want to put it first, he wants to put it above the div before it. So the previousSibling. It's a good start for him tho.
  • in this code, when you click on DIV 3, the DIV 3 swap's with DIV 1 instead of DIV 2..
  • glad, you were able to modify it to your case
  • This is pretty much what's already been answered, but I'm voting you up because you give a good complete answer.
  • Just what I was looking for
  • previousSibling will usually be a whitespace Text node (except on IE).
  • true, but then just test the nodeType, and if it's 3 get the previousSibling (if available) until you found one of nodeType 1. That's not too difficult.
  • I'm not sure it would work if one of these element has no previous sibling because no whitespace between the elements