简体   繁体   中英

Comparing the InnerHTML of an object in jQuery

I am able to get the .html() of a SharePoint textbox, which in the DOM simply appears as a <div> . When the textbox is empty, the InnerHTML of that <div> simply appears as <p></p> .

Because this particular textbox does not always appear (I control its appearance based on the selected value of a previous checkbox on the form), I can't make it required, so I'm doing it dynamically by checking if it is filled in or not on-save. This means seeing if that InnerHTML is <p></p> or something like <p>asdf<span id="ms-rterangecursor-start" RteNodeId="1"></span><span id="ms-rterangecursor-end"></span></p> , where asdf is the text that is entered (SharePoint puts in all the gobbly-gook in-between).

What I thought I could do was to check it like this, with explainField representing the <div> as a jQuery variable, similar to what was done at http://makandracards.com/makandra/13445-compare-two-jquery-objects-for-equality :

var $divNode = $('div');
var $pNode = $('p');
var $testNode = $divNode.html($pNode);
if (explainField.is($(testNode))) { 
    // we got <p></p>
    return false;  // go no further
} else {
    return true;  // we're ok
}

But this comparison does not work. When there is no text, the statement should be met and return false. Instead, it returns true and thinks we have text when we don't. How can I make this comparison work and return false if it finds <p></p> ?

So, try the following which is a bit easier than what you were trying.

var $divNode = $('div');
var html = $divNode.html();

if ( $(html).children().length > 0 ) {
    alert ("not empty");
} else {
    alert ("empty");
}

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM