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?
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.
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.
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.
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.
In this case, document.getElementById('id1').appendChild(document.getElementById('id2'));
should do the trick.
More generally you can use insertBefore()
.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With