2

I have a question. How can I use the parentNode property multiple times?

I know that I can make something like this:

document.getElementById("mytag").parentNode.parentNode.remove();

Or something like this. My Problem is not that I can add more or less .parentNode to remove whatever I want to remove.

My Problem is that I want to create a user friendly app in which the user can self declare how many parentNodes should be removed.

At first I tried to add .parentNode by a loop. It doesn't work. At second I tried the same with the eval() function. Same result.

Is there a person who have a good solution how I can make this? It was very useful if there is a opportunity on which you only have to say the number of parentNodes.

Here a little example. What I will be done "automatically":

myFunction(..., ..., 3) {
    ...
    document.getElementById("mytag").parentNode.parentNode.parentNode.remove();
}

Or

myFunction(..., ..., 2) {
    ...
    document.getElementById("mytag").parentNode.parentNode.remove();
}

Or

myFunction(..., ..., 1) {
    ...
    document.getElementById("mytag").parentNode.remove();
}

Thank you very much.

I prefere a solution in pure JS. An additional jQuery solution would be also nice.

SidOfc
  • 4,552
  • 3
  • 27
  • 50
Micha93
  • 628
  • 1
  • 9
  • 22
  • You tagged jQuery but you're not using it, and did not mention accepting a jQuery-based solution—if that is the case, the tag shouldn't be used. – Terry Feb 28 '16 at 21:59
  • http://stackoverflow.com/questions/12980877/parents-without-jquery-or-queryselectorall-for-parents – jtrumbull Feb 28 '16 at 22:19

1 Answers1

2

This function should do the job:

function removeParent(element, num) {
    var parent = element;
    for (var i = 0; i < num; i++) {
        if (parent.parentNode) {
            parent = parent.parentNode;
        }
    }
    parent.remove();
}

You can test it on this page. For example, the stackoverflow logo. HTML structure is like this:

HTML
    HEAD
    BODY
        DIV.container
            DIV#header
                DIV#hlogo

Open the console, copy-paste the function, and then enter removeParent(hlogo, 4). Entire page will disappear :)

akinuri
  • 10,690
  • 10
  • 65
  • 102