开发者

Check if a DIV id exists with JQuery

Using Javascript I'm trying to test whether or not a DIV with the id "test_div" exists in the document.

I'm using

if (getElementById("test_div"))

in the below script to check if the DIV exists in the document. However it does not work. I don't have very much experience with Javascript; but from the research I have done it seems like my problem might have something to do with the nested function.

The script does work if I remove the

if (getElementById("test_div"))

Does anyone know how to check if a DIV with the id "test_div" exists in the document from within the function as shown below?

<div id="test_div"></div>

<script>
function loadInfo(){
var req = new Request({
    method:'get',
    url:'getinfo.php,
    开发者_运维百科noCache: true,
    onRequest: function(){

        if (getElementById("test_div")) {
            $('test_div').set('html', 'loading data');
        }

    },  
    onComplete:function(responseText, responseHtml){
        if (JSON.decode(responseText) != null){
            var data = JSON.decode(responseText);

            if (getElementById("test_div")) {
                $('test_div').set('html', data['test_div']);
            }

        }   
    },
    onFailure: function(){

        if (getElementById("test_div")) {
            $('test_div').set('html', '-');
        }

    }           
}).send();  
}
window.addEvent('domready', function(){
loadInfo();
});
</script>


You would have to do document.getElementById(id). But seeing how you are using jquery - you could also do $(id).length > 0 to check if the element exists


Your case is incorrect in your sample code. You should be invoking getElementById, with a lowercase d. Javascript is case sensitive.

If you're using jquery, make sure to prefix id with a #, like so $("#test_div"), so jquery knows you want to query for an element id.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜