Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cut and Paste" - moving nodes in the DOM with Javascript

Tags:

javascript

dom

I have html code that looks roughly like this:

<div id="id1">   <div id="id2">     <p>some html</p>     <span>maybe some more</span>   </div>   <div id="id3">     <p>different text here</p>     <input type="text">     <span>maybe even a form item</span>   </div> </div> 

Obviously there's more to it than that, but that's the basic idea. What I need to do is switch the location of #id2 and #id3, so the result is:

<div id="id1">   <div id="id3">...</div>   <div id="id2">...</div> </div> 

Does anyone know of a function (I'm sure I'm not the first person to require this functionality) that can read and write the two nodes (and all their children) so as to swap their location in the DOM?

like image 695
user41435 Avatar asked Nov 27 '08 17:11

user41435


People also ask

How do I grab an element from a DOM?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.

Can you traverse the DOM through Javascript?

Having the access to a certain node in the DOM, there are ways to traverse through the DOM using its related nodes. We can move up or down the DOM tree, or we can move sideways staying at the same DOM level.

What is DOM node in Javascript?

The DOM Node interface is an abstract base class upon which many other DOM API objects are based, thus letting those object types to be used similarly and often interchangeably. As an abstract class, there is no such thing as a plain Node object.

CAN node JS manipulate DOM?

You can't use code running in Node. js to manipulate the DOM that a browser has built, or directly handle a click on a button rendered in the browser because both the button and DOM will be in the browser and not in the Node. js program.


2 Answers

In this case, document.getElementById('id1').appendChild(document.getElementById('id2')); should do the trick.

More generally you can use insertBefore().

like image 85
Greg Avatar answered Sep 18 '22 14:09

Greg


This function takes any node that is passed into it and wraps it with the tag given. In the example code snippet I wrapped a span tag with a section tag.

function wrap(node, tag) {   node.parentNode.insertBefore(document.createElement(tag), node);   node.previousElementSibling.appendChild(node); } 

function wrap(node, tag) {    node.parentNode.insertBefore(document.createElement(tag), node);    node.previousElementSibling.appendChild(node);  }  let toWrap = document.querySelector("#hi");  wrap(toWrap, "section");  console.log(document.querySelector("section > #hi"), " section wrapped element");
<span id="hi">hello there!</span>
like image 25
zfrisch Avatar answered Sep 17 '22 14:09

zfrisch