jquery - finding if element is in variable

自闭症网瘾萝莉.ら 提交于 2019-12-24 08:02:14

问题


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


来源:https://stackoverflow.com/questions/4624090/jquery-finding-if-element-is-in-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!