Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check Ajax success response before printing it out

I am getting some html code with div blocks out of a Ajax call. I would like to build a if/else check on this html, more specifically on the id attribute of a div returned. I would print different results if it’s either smaller or bigger than 10.

The html to be returned from the ajax call:

    <div id="10" class="names">Text</div>
    <div id="2" class="names">Text</div>
    <div id="10" class="names">Text</div>
    <div id="11" class="names">Text</div>

Ajax call

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$.ajax({
  type: "POST",
  url: "https://example.com/api",
  data: data,
  cache: false,
  success: function(html) {
    //check html response for the id attribute, print html after the check 
  },
  error: {}
});

Any idea how to do that?

>Solution :

Something like this?

note you have two id="10"

const html = `<div id="10" class="names">Text</div>
<div id="2" class="names">Text</div>
<div id="10" class="names">Text</div>
<div id="11" class="names">Text</div>`

function success(html) {
    //check html response for the id attribute, print html after the check 
   const res = $("#content").html(html)
   .find("div")
   .map(function() {
     return $(this).attr("id")
   }).get();
   console.log(res,res.includes('10') ? 'has id 10' : 'does not have id 10')
}

success(html)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="content"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading