Reputation: 91
I am pretty new to jquery/javascript and pretty much have to dig for an hour to write what i need, so in an attempt to save time, i am trying to write a conditional statement to check the class of an element and also that the "type" attribute is "text". This statement worked when I was just chacking .hasClass, and brok when adding && .is('[text]'). Is my syntax wrong? I have this, but it is not working:
if(!$("input").hasClass("input-block-level") && .is('[text]')) {
$("input").addClass("input-block-level");
}
my reason for doing this is that we have input fields that are dynamically added via python and TMPL_VAR. This is just a band-aid until the other team member can get the python script changed, but also as a fall back if we miss it somewhere else :)
Upvotes: 2
Views: 414
Reputation: 4552
Is this what you looking for?
if(!$("input:text").hasClass("input-block-level")) {
$("input:text").addClass("input-block-level");
}
Upvotes: 1
Reputation: 388316
From what I understand you are trying to add a class input-block-level
to input
elements which does not have the class and has type text
a simple one liner will do
$('input:text').not('.input-block-level').addClass("input-block-level");
Upvotes: 2
Reputation: 2216
The addClass() method adds the class, but it won't duplicate it. You can go with:
$("input[type='text']").addClass('input-block-level');
The function will cycle through all text input elements and adds the class. It's a good solution if you have a lot of inputs.
The addClass method will check if the element has the class on it's own, you don't need to check it before.
Upvotes: 2
Reputation: 11371
You might want to change the condition to this :
var $input = $("input");
if($input.hasClass("input-block-level") && $input.is('input:text')) {
//your code
}
Or, you could change your selector to get elements of type=text
alone :
var $input = $("input[type=text]");
if($input.hasClass("input-block-level")) {
//your code
}
Another good way to do this is using filter
:
$("input[type=text]").filter(":not(.input-block-level)").addClass("input-block-level");
Upvotes: 3