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 > 0to check if the element exists