Search code examples
javascriptjqueryvariablesdom-traversal

jquery - finding if element is in variable


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?


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