I need to check for an element with a css class being in existance on my HTML. I’ve Googled and searched here, and the common answer is to use .length > 0.
But that doesn’t work. I’m getting an “Object expected” error. Any help greatly appreciated.
<script type="text/javascript">
if ($(".deleteLink").length != 0)
{
$(".deleteLink").click(function () { return confirm('some message?'); });
}
</script>
.deleteLink is a css class that belongs to a tag that may or may not be present. I’m getting the error on the conditional part.
Am I missing somethign?? Because it seems that everyone says to use .length…
Checking
lengthis the correct way. There’s something else wrong with your code. Did you perhaps forget to include jQuery? Is something clobbering$? Run it in something better than IE to get a more meaningful error message.Also, a few tips.
if ($(...).length)is enough because 0 is falsy, no need for the comparison. Also, you don’t need to check if elements exist before manipulating them with jQuery (if it’s something lightweight such as just attaching an event handler). Manipulating an empty jQuery result doesn’t do anything.