Question

im trying to find out how to see if an error is returned from an AJAX request. for testing the request always returns <p id="error">test</p>

I thought you could do it like this:

//html is the var which contains the result
var DOM = $(html);
if( $('#error', DOM ).length != 0 ) {
    alert(html);    
}

but this does not work. Can anyone shine a light on whats going wrong?

Was it helpful?

Solution

If your HTML isn't wrapped in something (like a div) then it needs to be.

var html = '<div></div><p id="error">ERROR!</p><span>other stuff</span>';

var DOM= $('<div>' + html + '</div>');
if( $('#error', DOM).length != 0 ) {
    alert(html);    
}

Example: http://jsfiddle.net/jonathon/exqTD/

(I thought wrap would help here but it doesn't. If anyone knows why then point it out).

Alternatively, the selector context is implemented using find, so you could just do:

if( DOM.find('#error').length != 0 ) {
    alert(html);    
}

OTHER TIPS

It is not inserted to the DOM, so you cannot look it up with a selector.

You could try to use a simple regex with the test() function on the variable.

if (html.test(/id="error"/i)) {
   ...
}

Check if this will help:

$('body').append('<div class="hidden_div">'+html+'</div>');
if($('#error',$('.hidden_div')).size()>0){
  alert(html);
}

Just add in the css

.hidden_div{display:none;}

and that should be it, oh and you can use .length or .size()

or you can just use:

if(html.indexOf('id="error"')>-1){alert('yes we have an error!');}

Cheers

G.

You can use the find function:

if ( $(html).find("#error").length != 0 )
{
    alert(html);    
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top