In my current project i am getting xhr requests and i am placing them after an element like with this: el.insertAdjacentHTML('afterend', "foo bar");
but i haven't found a way to remove everything after the given element
, otherwise the markup will fill over.
I could wrap another container around it, but i am trying to use as less dom
elements as possible for performance reasons.
I found several solutions with JQuery
, this is not an option either, because its too huge.
Let's say i have a nav
element which is on top one its parent container and i want to place stuff after it, but before i have to remove the stuff which exists before.
Any ideas? Thanks in advance
searched the web and here, just found jq solutions, no vanilla js.
JS
el = document.querySelector("nav.mainNav");
el.insertAdjacentHTML('afterend', "foo bar");
HTML
<div>
<nav></nav>
<nav></nav>
<nav class="mainNav"></nav>
{...CONTENTSHOULD BE PLACED HERE, PLACING WORKS, REMOVING NOT...}
</div>
JSII - I am experimenting with something like this, but it seems that it does not select all elements. Suggestions?
var el = document.querySelectorAll("html > body >
nav.mainNav + *");
for ( var i = 0; i < el.length; i++ ){
el[i].remove();
}
I found my own solution, thanks four assistance!
var el = document.querySelectorAll("html > body > *:nth-child(1n+3)");
for ( var i = 0; i < el.length; i++ ){
el[i].remove();
}
An approach to this would be
el = document.querySelector("nav.mainNav");
var insertedContent = document.querySelector(".insertedContent");
if(insertedContent) {
insertedContent.parentNode.removeChild(insertedContent);
}
el.insertAdjacentHTML('afterend', "<span class ='insertedContent'>foo bar</span>");
Simply place the content within an element, and remove that element when you wish to replace, if it exists!