Jennifer
Jennifer

Reputation: 905

Check if a class or id exist in html response from ajax call

I know we can use hasClass() but in my case my ajax is returning html.

I can append then check the class exist or not but there'll be a flick. Is it possible to check what's inside the html before render it somewhere?

$.ajax({
  url:'some_url',
  success: function(html) {
    // I can do this:
    $('body').append(html);
    if ($('my_selector').length > 0) {
      // but I don't want to do this because I don't want that the html will show to the user
    }
  }
});

Upvotes: 0

Views: 4080

Answers (4)

Mosh Feu
Mosh Feu

Reputation: 29347

Further @Mohammad Adil answer:

var html = '<div class="test">This is the response from the ajax call.</div>';

function simulateAjax(selector) {
  var exist = $('<div />').html(html).find(selector).length > 0;
  $('#result').append('The element "' + selector + '" ' + (exist ? '' : 'not ') + 'exist<br />');
}

simulateAjax('.test');
simulateAjax('.test1');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>

The difference between the answers, and I think that the reason it didn't work for you, that for example: If your response is <div class="test"></div>, the @Mohammad's script will return false because there is no element with the class .test in the main element in the response.

So, you should wrap the response with element, then you can use .find() to check.

Upvotes: 1

Adil Shaikh
Adil Shaikh

Reputation: 44740

Yes, Possible

var yourReturnedHtml = getHtml();
return $(yourReturnedHtml).find('.someClass').length > 0;

Upvotes: 3

Moax6629
Moax6629

Reputation: 378

i got your point now. Use the same approach of hasClass() in success function of ajax and using async parameter. To remove the flick, place your ajax code is seTimeOut with time 0 like

setTimeout(function(){ //Your ajax code here }, 0);

Upvotes: 0

Alpesh Panchal
Alpesh Panchal

Reputation: 1713

Sure working method, used many time into my projects, This will help you find any elements, elements with some class or id.

You can append your ajax response to some hidden html element e.g div

e.g.

<div id="responseDiv" style="display: none"></div>

//Now write a function to save ajax response to div
//from this div, you can find out whether class or any element is there

$.ajax({
   url: 'some url',
   success: function(data){

      //save response to div
      $('#responseDiv').html(data);

      //now to check whether some class exists in the div
      if($('#responseDiv .class-to-find').length > 0){
           //since class is found into ajax response, write your code here

      }
   }
});

Upvotes: 0

Related Questions