3

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();
}
Sascha Grindau
  • 418
  • 2
  • 6
  • 18
  • Why not place a div after `mainNav` and change the contents of that? – Manav Jul 02 '19 at 12:32
  • 1
    One element more or less in the DOM is not going to have any measurable effect on performance. But if you are hellbent on finding a solution based on that kind of bogus reasoning, well then go locate the following siblings of your `.mainNav` element, and remove them one by one (should there be more than one.) – 04FS Jul 02 '19 at 12:34
  • Hm, how could i select them? – Sascha Grindau Jul 02 '19 at 12:37
  • i want to keep the markup small, i am beginning from scratch and mobile pages tend to get slow with a huge dom, so i start adding those wisely. I can add simple and easy with insertAdjacentHTML, but i want to remove the old stuff there before. ;) – Sascha Grindau Jul 02 '19 at 12:39
  • 1
    @SaschaGrindau My answer below should work for you – Manav Jul 02 '19 at 12:41
  • found my own solution and added it above. – Sascha Grindau Jul 04 '19 at 10:23

1 Answers1

4

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!

Manav
  • 1,357
  • 10
  • 17