jquery - finding if element is in variable

2019-07-28 15:20发布

问题:

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?

回答1:

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);    
}


回答2:

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)) {
   ...
}


回答3:

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.



回答4:

You can use the find function:

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