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.

Feel free to leave a reply here...

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: