-2

I want to check if an element exists on the page with a specified class (that's created dynamically.)

The simplest would be to do this, but since the elements doesn't exist on the page when the DOM loads, this won't work the way I want it to. (Hopefully I got that correct..)

if($('.list li').hasClass('//aDynamicallyGeneratedClass')){
//Then do this with my object.
});

Update: I'm running this inside an AJAX function which fetches data from MySQL. That function can be run even if the page doesn't reload so I don't want to use Document.onload.

Axel
  • 463
  • 6
  • 19

4 Answers4

1

Wait till document is loaded

$(document).ready(function() {
    if ($('.list li').hasClass('aDynamicallyGeneratedClass')) {
        console.log('exists');
    }
});
Miguel Mota
  • 20,135
  • 5
  • 45
  • 64
1

Are you adding the element to the DOM after the page is ready? If you so, you can just check if the element has the class as you described in your question.

However, if the element is being added before the DOM is ready, simply do this:

$(document).ready(function () {
   if($('.list li').hasClass('aDynamicallyGeneratedClass')){
     //Then do this with my object.
   });
});

When the DOM is ready, then this function will fire.
I hope this helps!
Cheers!

Jason Cidras
  • 509
  • 5
  • 11
0

Try this:

if ( $('.list li.YOUR_CLASS').length > 0)
{
   //Then do this with my object.
}

Replace YOUR_CLASS with what you want.

gioNicol
  • 339
  • 1
  • 10
0

You can simply do something like below:

$(document).ready(function() {

  if ($(".choose").is(".aDynamicallyGeneratedClass")) {

    $(".choose").css('color', 'red'); // Or something else

  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul>
  <li class="choose aDynamicallyGeneratedClass">One</li>
</ul>

This is just an example, study and adjust as needed

Sleek Geek
  • 4,638
  • 3
  • 27
  • 42