Check if div with certain class name exists

Using jQuery I’m programmatically generating a bunch of div’s like this:

<div class="mydivclass" id="myid1">Some Text1</div>
<div class="mydivclass" id="myid2">Some Text2</div>

Somewhere else in my code I need to detect if these DIVs exist. The class name for the divs is the same but the ID changes for each div. Any idea how to detect them using jQuery?


Without jQuery:

Native JavaScript is always going to be faster. In this case: (example)

if (document.querySelector('.mydivclass') !== null) {
  // .. it exists

If you want to check to see if a parent element contains another element with a specific class, you could use either of the following. (example)

var parent = document.querySelector('.parent');
if (parent.querySelector('.child') !== null) {
  // .. it exists as a child

Alternatively, you can use the .contains() method on the parent element. (example)

var parent = document.querySelector('.parent'),
child = document.querySelector('.child');

if (parent.contains(child)) {
  // .. it exists as a child

..and finally, if you want to check to see if a given element merely contains a certain class, use:

if (el.classList.contains(className)) {
  // .. el contains the class