jQuery : To check if an element is present in the page or not


This is a precautionary measure that you can adopt, if you are doubtful about the presence of a particular control in the page. Under normal scenarios, in case if the element is not there, it would throw an error. But you can now check if that particular element is present in the page or not, by just using the html() method in jQuery. Check the code snippet below:

<html>
<head>
<script language=”javascript” src=”jquery-1.3.2.min.js” type=”text/javascript”></script>
<script language=”javascript” type=”text/javascript”>
function fnoerror()
{
return true;
}
window.onerror=fnoerror;
$(document).ready(function(){
if($(“#x”).html())
alert(‘x exist’);
else
alert(‘x is missing’);
});
</script>
</head>
<body>
<div id=”x1″>
hello
</div>

<input type=”text” id=”xxx” value=’xcvxvcxcv’/>
</body>
</html>

When you load the page, it will throw the popup with the message ‘x is missing’. Now replace the id of the input textbox from ‘xxx’ to ‘x’ and load the page. The popup would show ‘x exist’ message. Hope this was useful.

How to suppress nagging javascript errors?


To suppress javascript error popups and warnings in your browser, just use the code snippet below:

<SCRIPT language=”JavaScript”>
<!–
function silentErrorHandler() {return true;}
window.onerror=silentErrorHandler;

//–>
</SCRIPT>

This however has some limitation, from what i had experienced. It works well in IE, to a major extend in Firefox, but not much in Opera and Safari. Hence it would be advisable you use the jquery error handling in addition, to be on the safer side:

$(window).error(function(){

return true;

});

As far as i have seen, jquery error handling function works pretty well in all the browsers.

I would recommend you to use this only in the final production stage and not during development. Just for the simple fact that during development you would want to find the javascript errors.