css :not() selector with selector list incoming - javascript

I have many css selectors and many selector exception, so I use :not to leave them out...
example (just some selectors I don't need):
[class*="-dashboard-"]:not([class$="-binding"]), [class*="-dashboard "]:not([class$="-binding"]), [class$="-dashboard"]:not([class$="-binding"])
But what I instead would prefer is:
([class*="-dashboard-"],[class*="-dashboard "],[class$="-dashboard"]):not([class*="-binding-"],[class*="-binding "],[class$="-binding"])
or something else, that ist shorter than the working one and easier to edit and not so repetitive...
My problem is that I have that selectors in big list. The user is allowed to add/remove lists so I have to dynamically change the selectors and exceptions.
Does anybody have an idea to short that one???

Usually, the way my CSS looks is with increasing specificity. A very generic rule sets a whole lot of defaults, and then something that positively matches one of those rules you gave us overrides that style with something else.
For instance, you could set a higher-priority rule for anything ending in "-binding" that makes elements invisible, or whatever you intend for them. In simple terms, to calculate a CSS rule's priority:
Add 100 for each ID selector
Add 10 for each class selector
Add 1 for each other selector
I think you'd do well by having more classes in your elements that are easily selected, ie anything that adds a lolwtf-dashboard class should also add a dashboard class that's easily CSS-selected.

Related

Select Elements Numerically Dynamic in jQuery

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.

jquery allow only one of a group of classes on an element?

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';

How to remove all pseudo selectors from a CSS selector string using Javascript?

For a script I'm doing I need to verify a CSS selector exists in the DOM. I'm wondering how to handle multiple :pseudo selectors with a generic rule.
Something like this is simple:
var selector = "div.foo div.bar:active"
which could be handled by
selector.split(":").shift(); // > div.foo div.bar
but when I have multiple selectors, I'm don't know how I could remove them. Something like this:
var selector = "div.foo:hover div.bar:after"
Question:
How would I remove all CSS pseudo selectors (":something") from a string?
You can remove them with a regular expression and replace:
selector = selector.replace(/::?[^ ,:.]+/g, '');
(The ::? means one or two colons [you could also write it as :{1,2}], to handle ::after and such; full regex explanation.)
That works for most situations, but if you have really complex pseudos with nested pseudos like foo.bar:not(.baz:active) (will be in CSS4), you'll need an actual CSS selector parser to handle them properly. While you could probably build a regex alternation that would handle one bit of nesting, in theory there can be multiple nesting, which is where a parser comes in.
But note that some of these pseudos do affect which element is chosen, such as :nth-child, so if your goal is to see if a matching element is in the DOM, you wouldn't want to remove those. So you might want to take the fairly pragmatic approach of listing the ones that you want to remove in a series of alternations, e.g.:
var toRemove = /:hover|:active|:before|:after|::?before|::?after|:and-so-on/g;
// ...
selector = selector.replace(toRemove, '');
There aren't all that many, and it eliminates the chance of removing important structural ones line :nth-child.
Removing all pseudo-selectors will not solve your problem.
Take this example:
p:first-child {}
<div>
<div></div>
<p></p>
</div>
Since the paragraph is not the first child (and won't be unless the DOM changes), removing :first-child from the selector will give you a false positive match.
You need to remove only the pseudo-classes which are conditional upon things like mouse or keyboard interaction and the psuedo-elements. Then you need to special case :link and :visited so that the match anchors that are links and not ones that aren't (replacing them with an attribute selector of [href] is a slightly naïve approach, but should be good enough for all practical purposes).
You'll also need to make a decision for :enabled and :disabled. They aren't going to be changed by user interaction, but if you plan to toggle them with JS then you'll probably want to remove them.
Since there are a lot of conditions here, I'd write a function for it rather than attempting a simple regex.

Best way to dynamically add and remove style on elements

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

Which is better practice for adding a class using jQuery?

$("#" + 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.

Categories

Resources