-1

Example -

<div class="main"></div>
<div class="main child"></div>

On chrome devtools document.querySelectorAll(".main") selects main & main child.

How can I select only main?

heyheyhey2
  • 29
  • 5
  • 1
    Don't put the class `main` on the second element if you don't want it to be selected? – Bergi Jul 05 '22 at 12:40
  • Please post the complete code - what selector are you using with `querySelectorAll`? We can't help you fix it if you don't tell us. – Bergi Jul 05 '22 at 12:40
  • 1
    I'm scraping from a website I don't control that. @Bergi – heyheyhey2 Jul 05 '22 at 12:40
  • what query are you using? – derpirscher Jul 05 '22 at 12:41
  • 1
    It's not a child, it's a sibling, fwiw. A child would be _inside_ the first `div`. – Andy Jul 05 '22 at 12:42
  • 1
    We only know what you tell us in the question. [Edit] your question to include all constraints you are under, and a [mre] (preferably in a [Stack Snippet](https://meta.stackoverflow.com/q/358992/215552)). – Heretic Monkey Jul 05 '22 at 12:45
  • A better solution would be to use `document.querySelectorAll('[class="main"]')` if you actually want elements that have the one and only class "main". – Heretic Monkey Jul 05 '22 at 12:53

1 Answers1

3

Use .main:not(.child) to select only those elements that have the main class but not the child class.

console.log(document.querySelectorAll('.main:not(.child)'))
<div class="main"></div>
<div class="main child"></div>

Read more about :not() on MDN

Thomas
  • 174,939
  • 50
  • 355
  • 478
  • 2
    Yes it is -- added a demo. – Thomas Jul 05 '22 at 12:44
  • This (and the duplicate) answers the question in the most literal reading of the question, but not the actual question asked: "How can I select only main?" If there are hundreds of elements, each with main and one or more other unique classes, the selector would soon grow unmanageable. – Heretic Monkey Jul 05 '22 at 12:49