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.

Center aligning div elements


Well, in most of the scenarios in a web designing art, you might come across one wherein you have to center align a div tag, without affecting the text in it. Your first thought might be text-align:center;

But if you want to center align the div alone, leaving the text alignment to be unaffected, you can use this trick css styling. Just give the margin of the div as : margin:0 auto; Lol… done.

It goes well for all browsers.

Thats all… you can now center align a div without affecting the text-alignment of the div contents.