user759235
user759235

Reputation: 2207

How to check if an variable is an class or id(jQuery)

I am building a jQuery plugin and i'm using a variable in it which can be an class or id. I dont want to use the . or # in the variable, so is there an way to check if an variable is a class or id.

Coudn't find anything on the web about this.

some of the code

var defaults = {
    trigger: ''         
};

var opt = jQuery.extend(defaults, opt);

jQuery(opt.trigger).click(function(){
//run code
});

Upvotes: 1

Views: 1031

Answers (3)

user415715
user415715

Reputation:

Something like this?

if(document.getElementsByClassName(your_vairable).length != 0){
    // It's a class
}
else if (document.getElementById(your_variable) != null){
    // It's an id
}
else{
   // Oh god what have you done
}

Upvotes: 3

ShankarSangoli
ShankarSangoli

Reputation: 69905

Check for

if($("#"+variable).length){
   //It is an id.
}

Upvotes: 2

slandau
slandau

Reputation: 24052

No, unless you scour the CSS on the page and match it to a class, but who's to say you can't identify something the same as a class name?

I would do something like (this is a function but you can apply to a plugin):

function passIdentifier(id, isClass)
{
    var selector;
    if (isClass)
    {
        selector = '.' + id;
    }
    else
    {
        selector = '#' + id;
    }
}

Upvotes: 0

Related Questions