views:

72

answers:

2

Currently I use this to check if a tab(element) already exists:

if(!$('#'+element).length){
   //... code to add new tab if not exists.
} else {
   Alert("Tab or portlet already exists...");
}

This is very dirty and I get a "uncaught exception: Syntax error, unrecognized expression: #" from FireBug. If element already exists, the "Alert" doesn't show, I think it hangs at the first exception.

Is there a better way to check if an element exists? (Or a tab)

I am using this for my personal project @ http://www.soliman.nl/test/jqueryui/ui_2.php

A: 

hi please check value of element

coz if this is null or empty your statement become

if(!$('#').length){
or
if(!$('#null').length){

which may through some error

here is working version

​<html>
<body>
    <p id="test"></p>
</body>
</html>

​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

var element = "test"; //if you try to comment this line or change value , it will give error 
if(!$('#'+element).length){
   alert("do something");

} else {
   alert("Tab or portlet already exists...");
}​

Demo http://jsfiddle.net/J3MdK/

JapanPro
You need to comment your comment in the `var element` line.
RickF
A: 

The problem seems to be in your source - you are passing "#foo" as the parameter element, then prepending another "#". The result is $("##foo"), which just isn't going to work.

RickF
lol ;-) thank you!
Soliman