$("#" + parentElementId + " label").attr("class", "disabled")
VS
$('#radiolabel').addClass('disabled');
Which are the pros and cons?
Thanks
The two are not the same. Using attr will replace the whole attribute. addClass will add the class to the existing classes.
As the name suggests addClass is made for this specific purpose, so I'd use that.
Here are some advantages of the two ways to do this:
addClass("disabled") Pros:
If you have other classes on your object, addClass() will preserve those while adding a new class. I pretty much always want to preserve the ability to use other classes for CSS styling reasons or common selector reasons so addClass() makes it possible to add the disabled class without disturbing other classes on the same object for other reasons.
The code reads a little more self-explanatory since the name addClass() tells someone reading the code exactly what it's doing.
addClass() automatically manages separators between class names so there is no extra accumulation of separators when you have multiple class names which can occur if you just get the current classname and add onto it yourself with string manipulation.
attr("class") = "disabled" Pros:
If you only ever want one class name on the object, this one statement insures that you will have only one class name.
A direct assignment of the one class can be faster than addClass() which has to examine what's there first and add a class to the pre-existing classes which jQuery does with a regex match. Max speed would actually be with element.className = "disabled" (no jQuery at all).
I'd go for addClass, it's easier to read, and if your editor supports code completion, also faster to type.
You better go for the addClass() you will save time and writting, and gain more efficiency.
Related
I'm just wondering how I can select elements in jQuery dynamically, for example here is a selector of mine:
$("#video_background_video_0, #video_background_video_1, #video_background_video_2, #video_background_video_3, #video_background_video_4").remove();
As you can see this isn't the best example of DRY programming, I'd like to create a selector that selects all elements that begin with #video_background_video_. I basically just want to select the above elements in the cleanest way, I was wondering if there is a way that I can dynamically select these elements with some sort of count instead of placing all of my selectors like so, it just looks very messy and I'm wondering if there is a better way to do this when it comes to elements with a numeric ending?
As jQuery uses a CSS selector syntax I am unsure how I can do this.
Thanks, Nick
You can use start-with selectors:
$('[id^="video_background_video"]').remove();
There are other attribute selectors you might be interested here.
Try to use attribute starts with selector,
$("[id^='video_background_video'")
Also make sure that, this selector is not a native css based one. It will fetch the elements after executing regular expressions internally. So it would be better to use it in a minimum level. Its Better to set a common class to those elements and use class selector instead.
I have an element that gets a number of classes added to it + removed from it dynamically using jQuery. I'd like to ensure that I have only one of a set of classes on the element at a given time.
For example, I could have the .blue_element class that defines a font color, background color, border color, etc., and I wouldn't want that on the element at the same time as a .red_element class or a .yellow_element class, but I wouldn't mind it being on at the same time as a .small_element class or .big_element class.
Current method:
$('#target_element').removeClass('yellow_element').removeClass('red_element').addClass('blue_element')
This works fine but seems like it creates a risk for error, e.g. if I add a .purple_element class but forget to modify my removal code.
I'm doing this on a larger scale than in my example and may be adding and removing classes quite frequently, so I'd expect to make some boneheaded mistakes if I do it this way. Is there a more efficient way to do this?
Instead of using jQuery use native mathod
document.getElementById("target_element").className = 'blue_element';
Above code will remove all classes and keep/add only 'blue_element';
Okay, I've got an interesting one (well, interesting to me, anyway :) ).
I've got a situation where I have a div with a static class value, but it also can have a single, "secondary class" assigned that is dynamic. When the user makes a selection, any existing secondary class needs to be removed and the new class added.
Ignoring using an id value (standards for the project use the class . . . can't be changed), is there an elegant way to simply ignore the first class and remove whatever other class is there, before adding the new one?
Example Starting HTML:
<div class="staticClass dynaClass1" />
Example JS:
function updateClass(newSecondaryClass) {
$(".staticClass") . . . **** remove any class besides "staticClass" ****
$(".staticClass").addClass(newSecondaryClass);
}
If the function is called using updateClass("dynaClass2");, the resulting HTML should be:
<div class="staticClass dynaClass2" />
I can think of ways of doing it involving just removing all classes using removeClass(); and adding "staticClass" back in when adding the new class, or using attr("class", "staticClass " + newSecondaryClass);, but I'm wondering if there isn't a way to handle it without having to touch the static class at all?
In the end, I guess this is an academic question, more than anything . . . just seems like it's something that should be doable, but I don't know how to do it. :D
You can remove all classes and add the one you want to leave:
$(".staticClass").removeClass().addClass('staticClass');
Calling removeClass() without a parameter removes all classes.
If you don't want to do that then you can simply modify the class attribute:
$(".staticClass").attr('class', 'staticClass');
You can pass a function to remove class, which returns all but the static Classes:
$('.staticClass').removeClass(function(index, klass) {
return klass.replace(/(^|\s)+staticClass\s+/, '');
})
This is returning all the classes that are on the object, without the static one, and therefore removes all classes but the static one.
Pass a function to .removeClass()
A revision of Beat Richartz's answer on this page.
Note: I tried to post this as an edit and it was rejected. The concept is identical, with an improved RegEx.
Improved RegEx provides word-boundary matching with multiple classes
// Remove all classes except those specified
$('span').removeClass(function () {
return $(this).attr('class').replace(/\b(?:hello|world)\b\s*/g, '');
});
Before:
<span class="hello foo">hello</span> <span class="world bar">world</span>`
After:
<span class="hello">hello</span> <span class="world">world</span>`
Try it: http://jsfiddle.net/gfullam/52eeK/3/
Try it as a jQuery plugin: http://jsfiddle.net/gfullam/52eeK/5/
FWIW: This method is necessary when you don't want to replace the existing classes with other classes as in .attr('class', '<final list of classes>'), but instead just want to remove those that don't match a list of classes.
You can set it's required classes using the .attr() function. So:
$('.staticClass').attr('class','<any classes required');
This will replace any classes that were originally there, and add the new ones.
All of your classes are manipulated by calling the Javascript DOM element.className, so basically jQuery's addClass just replaces that string. You can see that in the Github source.
Which all means that if you call
$('.staticClass').addClass('someClass');
The element.className is replaced anyway, but with the new class included. ( this means that your staticClass is actually touched :)
When you call
$('.staticClass').removeClass().addClass('staticClass');
you will replace that string twice and there is no problem doing that.
I am using mouseenter and mouseleave events on some elements to change their appearance. I am able to do so using either of the following two strategies:
$(this).css('someProperty','someValue') to add and then $(this).removeAttr('style') to remove
$(this).addClass('someClass') to add and then $(this).removeClass('someClass') to remove
What is the best way to do so?
Definitely option 2. Styles should be defined in the stylesheet.
There's also toggleClass, which removes the class if it's there, but adds it if it's missing.
Note: toggleClass also lets you pass in a Boolean as the second argument, telling it whether to add or remove it (regardless of whether it currently has that class applied), so:
$(this).toggleClass('active', true);
is exactly equivalent to:
$(this).addClass('active');
This is very handy when you have a Boolean in your code already. So instead of this:
if (isUserActive()) {
$(this).addClass('active');
} else {
$(this).addClass('active');
}
You could just do this:
$(this).toggleClass('active', isUserActive());
Option 2 if you must do it in JavaScript, but for modern browsers you may be able to achieve what you're after entirely in CSS using :hover pseudo-classes.
I'd strongly recommend addClass()/removeClass(), since you can add, remove and change a whole swathe of properties with minimal jQuery.
Whereas the css() method requires you, or rather the script, to keep track of what should be changed to reflect the aesthetic change(s) to convey programmatic interaction, coupling that with the attr() method and removing the style attribute will remove all styles, even those you want the element to retain, which requires you to reassign those properties.
So, basically, option 2 is efficient, and option 1 creates unnecessary work.
There is, of course, always toggleClass(), which can promote further efficiency.
Unless you need to dynamically generate any of the CSS property values you're better of separating the styles from the javascript. So use classes instead of direct css styles.
.addClass and .removeClass is the best way because you can style you changes with your CSS ...so after a while you can easily redesign your site.
Second one is best because normally style will is common for different elements, it will generic and adding removing is good compared with adding attribute one by one.
$(this).addClass('someClass') to add and then $(this).removeClass('someClass') to remove
If you are calling this function in more than one element I suggest you to use the second one. If you needed to change the appearance again later, then you have to edit only within the css class, not in all elements
I'm wondering if these two expressions are equivalent, because if they are, it would make this much easier.
$('div', this).filter(':not(.trigger)')...
$('div:not([class*=trigger])', this)...
(this providing a context under which to look for the specified div)
No.
Version 1 takes all divs without the class trigger.
Version 2 takes all the divs where the attribute class contains the text trigger.
This means a div with the class mytrigger will be a match.
Selectors
EDIT
With your updated question this would be the equivalent to the first version.
$('div:not(.trigger)', this)
They're not essentially the same. The second also filters out all div's which have a class which contains "trigger" in the name, thus also e.g. "anothertrigger" and "triggerfoo".
You can also use
$('div:not(.trigger)', this)...
which is imho much clearer.