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" >Text</div>
<div id="2" >Text</div>
<div id="10" >Text</div>
<div id="11" >Text</div>
Ajax call
$.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?
CodePudding user response:
Something like this?
note you have two id="10"
const html = `<div id="10" >Text</div>
<div id="2" >Text</div>
<div id="10" >Text</div>
<div id="11" >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>