2

I'm trying to simply get all of the first divs while exlcuding the second divs:

<div class="_5pcr userContentWrapper">
<div class="_5pcr userContentWrapper _4nef">

I searched and fout of that the querySelector function should be doing the job. However I tried it with multiple inputs, but all of those result in an empty list. If I use the DOM function getElementsByClass it works but then of course I got all divs, also the second ones that I don't want. Here are the querySelector function calls I tried:

listOfPosterName = document.querySelectorAll('div._5pcr userContentWrapper:not(._4nef)');
listOfPosterName = document.querySelectorAll('DIV._5pcr userContentWrapper');
listOfPosterName = document.querySelectorAll('_5pcr userContentWrapper:not(_4nef)');
listOfPosterName = document.querySelectorAll('DIV.userContentWrapper:not(_4nef)');

I have even tried to just get the same result as with "getElementsByClass('_5pcr userContentWrapper')" with this:

listOfPosterName = document.querySelectorAll('_5pcr userContentWrapper');

That also did not work. I thought it's a problem because of the space between the classes, but I tested it also with a single class.

I really appreciate help!

Lennie
  • 253
  • 6
  • 16
  • https://stackoverflow.com/questions/21975881/how-to-select-element-that-does-not-have-specific-class – Shashikiran May 20 '18 at 01:27
  • *getElementsByClassName* just looks for elements with matching classes based on a space separated list, it can't exclude matches based on some other criterion (e.g. the `:not` pseudo–class). – RobG May 20 '18 at 01:43

3 Answers3

4

You are not writing the selectors correctly.

When you want to select an element having multiple classes you would do:

document.querySelectorAll('.class1.class2.class3');

When you leave a space character in a selector - it becomes what is called a descendant selector. Example:

<div class="class1">
  <p class="class2"></p>
</div>

In this case, class2 could be selected with a descendant selector:

document.querySelector('.class1 .class2');

Your fixed example could look like so:

<div class="_5pcr userContentWrapper">
<div class="_5pcr userContentWrapper _4nef">

document.querySelectorAll('._5pcr.userContentWrapper:not(._4nef)');
bcorbella
  • 271
  • 2
  • 7
3

Your problem is just putting too much spaces where unnecessary:

  listOfPosterName = document.querySelectorAll('._5pcr.userContentWrapper:not(._4nef)');
Gregoire Lodi
  • 557
  • 2
  • 10
1

querySelector() works just fine, but you have to pass it the selector properly. Multiple classes should be concatenated together, not space separated like in the HTML.

document.querySelector("._5pcr.userContentWrapper").classList.add("selected");
.selected { background-color:yellow; }
<div class="_5pcr userContentWrapper">Me</div>
<div class="_5pcr userContentWrapper _4nef">Not Me</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71