taoqf / node-html-parser

A very fast HTML parser, generating a simplified DOM, with basic element query support.
MIT License
1.12k stars 112 forks source link

How to remove current element #85

Closed akelmj closed 4 years ago

akelmj commented 4 years ago

Hi, I have this code:

let div = selector.querySelector("#divid");

i want to remove the div like:

div.remove();

is there any way to do that?

taoqf commented 4 years ago

I suppose you are an user of jquery. see this example, or just use method remove.

akelmj commented 4 years ago

thank you for your fast response :+1:

what if i want to delete an element without parent:

example: `

.... ` in this example if i use the remove method it will NOT work: `let custom_element = selector.querySelector("customElement"); custom_element.remove(); `
taoqf commented 4 years ago

Sorry, I don't get your point. and, what's the example?

akelmj commented 4 years ago

the remove() method remove only child element.

example that wok:

`

`

`let custom_element = selector.querySelector("custom");

custom_element.remove();`

example that NOT work (the custom tag outside the HTML):

`

` the same code not remove the custom tag: `let custom_element = selector.querySelector("custom"); custom_element.remove();` I hope that i explained well. [custom.txt](https://github.com/taoqf/node-html-parser/files/5516555/custom.txt)
taoqf commented 4 years ago

Yes, you explained well. This is not a simple issue, the reason is the element has not get a parent. Actually, it do has a root node called 'Root', but the element has no parent for most users, see code:

response.childNodes.forEach((node) => {
    if (node instanceof HTMLElement) {
        node.parentNode = null;
    }
});

I don't know if we can change some code here, and just make remove seems right.

taoqf commented 4 years ago

Maybe that will also make sense.

taoqf commented 4 years ago

try v2.0.0, good luck!