Is there any way to check if an element has jquery select2 already applied to it?
Working solution:
$('.MyDripdowns:not([class^="select2"])').each(function (i, obj) {
$(obj).select2({width: "455px"});
})
Links:
- ^= attribute starts with selector
- :not selector
you can check if the element has select2
attribute
$('.MyDripdowns').each(function (i, obj) {
if (!$(obj).data('select2'))
{
$(obj).select2({ width: "455px" });
}
});
EDIT
As @Fr0zenFyr said in his comment for v4.0 you can use :
if (!$(obj).hasClass("select2-hidden-accessible"))
Above answer is almost correct.
But it creates problem when we are adding elements dynamically on same page and applying select 2 to newly created element.
At that times selector has to be specified using not only class but also with input type. PFB reference code.
$('inputp[type="text"].MyDripdowns').each(curr_idx, curr_elem){
//Check if select 2 is already applied or not
if($(curr_elem).hasClass('.select2-offscreen')){
//Select 2 is already applied to this element
}
else{
//Apply Select 2 to this element
}
}