Goutham
Goutham

Reputation: 53

How to select all elements except all <p> elements and all their children using JavaScript?

I want to use a javascript dom selector method like getElementsByTagName to select all elements except all <p> elements and all their children and I'll be using this for some specific scraping requirements in certain webpages.

Upvotes: 0

Views: 78

Answers (2)

L. Monty
L. Monty

Reputation: 882

document.querySelectorAll('*:not(p, p *)')

the :not(..)-pseudo-selector will exclude elements matching the selector in parenthesis.

Also see Mozilla documentation of :not()-pseudoselector

Upvotes: 1

vptest
vptest

Reputation: 296

const elements = document.querySelectorAll('*'); // Selects all elements
let filteredElements = []; // array only with needed elements

for (let i = 0; i < elements.length; i++) {
  if (elements[i].tagName !== 'P' && !elements[i].matches('p  *')) {
    filteredElements.push(elements[i]); // Checks if processed element is not <p> or a child of it on any depth level
  }
}

A code like this should do the job. Lines are self-explanatory pretty much, but I added some comments there.

Upvotes: 0

Related Questions