jQuery selector on multiple classes - javascript

This finds the id but does not remove the class
$('[id^=paritalIDname]').removeClass('[class^=partialClassName]');
Probably because the element looks like
<div id="partialIDname-full" class="something someone partialClassNameFull">
Whether the element has a class name of partialClassNameFull or partialClassNameHalf I need to remove it.
I thought I could use a wildcard in the class selector, like
removeClass('[class^=partialClassName*]');
but that's not working.
What is a good solution? (Thanks.)

This will handle all partial match.
$("div[id^=partialId]").each(function () {
var cls = $(this).attr("class").split(" ");
for (var i in cls) {
if (/partialClass/.test(cls[i])) {
$(this).removeClass(cls[i]);
break;
}
}
});

You need to explicitly remove both classes:
$('[id^=partialIDname]').removeClass('partialClassNameFull').removeClass('partialClassNameHalf');
Because .removeClass() only works on full class name matches. If one of the class names is not present, then nothing will happen - no error is thrown when you try to .removeClass() a class that is not present.
You can also try out as suggested in the comments the briefer version of:
$('[id^=partialIDname]').removeClass('partialClassNameFull partialClassNameHalf');

Related

correct jquery syntax on the each of the selector for checking class

I am trying to check for a class if it not exists then do some work, else skip it over
$.each($(":not textarea.hasClass('encypted')", "#"+formID),function(k){
do the code part
});
what i am doing here is to check if the textarea does not have a class encypted and only then go inside and do its work, if it has that class, just skip the entire code part
You can use :not() to directly select the textareas which do not have the given class:
$(`#${formID} textarea:not(.encrypted)`).each(function() {
// your code here...
});

jQuery Find and Replace all instances of part of a classname

I have several div's with a classname that looks like this:
class="col-md-4"
some have:
class="col-md-12"
What I want to do is to search for whatever the number at the end of the class is and replace all of them to:
class="col-md-6"
How can I do this using jQuery?
You can use special selectors in jQuery:
^= starts with ...
*= contains ...
Or use a combination of both selectors if you don't get them all.
var cols = $('[class^="col-md-"]');
Then to remove all classes with a wildcard
cols.removeClass(function (index, css) {
return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
});
Then add the class you want:
cols.addClass('col-md-6');
Try to remove the class and add the new one:
$(".col-md-4").removeClass("col-md-4").addClass("col-md-6");
$(".col-md-12").removeClass("col-md-12").addClass("col-md-6");
you can use "contains" selector like this
$("[class*='col-md-']").removeClass (function (index, css) {
return (css.match (/(^|\s)col-md-\S+/g) || []).join(' ');
}).addClass("col-md-6");
removeClass function based on this answer
$("[class*='col-md-']")
will find any element with a class that contains col-md-.
The removeClass function will than remove it. And finally col-md-6 will be added.
EDIT
changed [class^='col-md-'] to [class*='col-md-'] in case class attribute has another class before col-md-. Thank you #dfsq for pointing this out
This should also work:
$('[class*=col-md]').removeClass('col-md-4 col-md-12').addClass('col-md-6');
You could do it with simple javascript if all of those elements were inside a main div.
For example:
var arr_divs = document.getElementById('main_div').getElementsByTagName('div');
for(var i = 0; i < arr_divs.length; i++){
if(arr_divs.item(i).className == 'col-md-12' || arr_divs.item(i).className == 'col-md-4'){
arr_divs.item(i).className = 'col-md-6';
}
}
This may not be the most efficient way of doing what you want but, it keeps it simple. Here's a working fiddle: https://jsfiddle.net/Lns1ob5q/
$("[class^=col-md-]").attr("class", "col-md-6");
The above selects all elements with a class containing col-md- ([class^=col-md-]) and replaces the class, regardless of what number immediately follows, with col-md-6.
The reason I say it's not efficient is becuase jQuery will initially pick up elements that already have a class of col-md-6 and replace their class with the same one... But hey, it works!

How can I use document.querySelector to select this class name with a space in it?

<a href="javascript:void(0)" class="PrmryBtnMed"
id = "VERYLONGTEXT"
onclick="$(this).parents('form').submit(); return false;"><span>Dispatch to this address</span></a>
I have been using
var inPage = document.documentElement.innerHTML.indexOf('text to search') > 0,
el = document.querySelector(".PrmryBtnMed");
if (inPage && el) el.click();
But now, the class name has changed: there’s a space and some new text in the class name:
<a href="javascript:void(0)" class="PrmryBtnMed ApricotWheat"
id = "VERYLONGTEXT"
onclick="ApricotWheat(this); return false;"><span>Dispatch to this address</span></a>
How can I change el = document.querySelector(".PrmryBtnMed");
to find the right class?
I tried using el = document.querySelector(".PrmryBtnMed.ApricotWheat"); but that didn’t work.
Next, I tried to add a space (and escape using a backslash): el = document.querySelector(".PrmryBtnMed\ ApricotWheat"); but that didn’t work either.
So, I wondered if I could use %20 for the space.. but no luck.
I’d be very grateful for some help! What am I doing wrong?
Classes can't have spaces, what you have there is an element with two separate classes on it. To select an element with two classes, you use a compound class selector:
document.querySelector(".PrmryBtnMed.ApricotWheat");
That selects the first element in the document that has both the PrmryBtnMed class and the ApricotWheat class. Note that it doesn't matter what order those classes appear in in the class attribute, and it doesn't matter whether there are also other classes present. It would match any of these, for instance:
<div class="PrmryBtnMed ApricotWheat">...</div>
or
<div class="ApricotWheat PrmryBtnMed">...</div>
or
<div class="PrmryBtnMed foo baz ApricotWheat">...</div>
etc.
Also note that the quotes you're using around HTML attributes are sporatically invalid; the quotes around attributes must be normal, boring, single (') or double ("), they can't be fancy quotes.
Live example with quotes fixed and using the selector above:
var el = document.querySelector(".PrmryBtnMed.ApricotWheat");
if (el) {
el.click();
}
function ApricotWheat(element) {
alert(element.innerHTML);
}
<span>Dispatch to this address</span>
There can be no spaces in a class name ... there are two different classes in the element ... use ".PrmryBtnMed.ApricotWheat"
class="PrmryBtnMed ApricotWheat" In this instance you have 2 different classes,
so you need to use the AND condition in your query.

jQuery select all classes except one ID

I need to select all divs of a certain class (jqx-slider) excluding one ID (#str_prg) - something like:
$("div.jqx-slider :not(#str_prg)").each(function () {
.....
});
What is the correct syntax for that?
Also, would it be faster and more effecient code, if I add a "if" condition inside the loop - like
if($(this).attr('id') ! = "str_prg"){
}
Thanks!
You are using an descendant selector between the class selector and the not selector, which is invalid for your requirement
$("div.jqx-slider:not(#str_prg)")
when you say $("div.jqx-slider :not(#str_prg)") it selects all descendants of elements with class jq-slider except the one with id str_prg
Try to remove an unnecessary space char like this:
$("div.jqx-slider:not(#str_prg)")
Remove the space, as it would cause you to select children, instead of the element itself.
$("div.jqx-slider:not(#str_prg)").each(function() {
.....
});
For the second part of your question, it would be better to just use the CSS selector instead of a JS loop.

Remove all classes except one

Well, I know that with some jQuery actions, we can add a lot of classes to a particular div:
<div class="cleanstate"></div>
Let's say that with some clicks and other things, the div gets a lot of classes
<div class="cleanstate bgred paddingleft allcaptions ..."></div>
So, how I can remove all the classes except one? The only idea I have come up is with this:
$('#container div.cleanstate').removeClass().addClass('cleanstate');
While removeClass() kills all the classes, the div get screwed up, but adding just after that addClass('cleanstate') it goes back to normal. The other solution is to put an ID attribute with the base CSS properties so they don't get deleted, what also improves performance, but i just want to know another solution to get rid of all except ".cleanstate"
I'm asking this because, in the real script, the div suffers various changes of classes.
Instead of doing it in 2 steps, you could just reset the entire value at once with attr by overwriting all of the class values with the class you want:
jQuery('#container div.cleanstate').attr('class', 'cleanstate');
Sample: http://jsfiddle.net/jtmKK/1/
Use attr to directly set the class attribute to the specific value you want:
$('#container div.cleanstate').attr('class','cleanstate');
With plain old JavaScript, not JQuery:
document.getElementById("container").className = "cleanstate";
Sometimes you need to keep some of the classes due to CSS animation, because as soon as you remove all classes, animation may not work. Instead, you can keep some classes and remove the rest like this:
$('#container div.cleanstate').removeClass('removethis removethat').addClass('cleanstate');
regarding to robs answer and for and for the sake of completeness you can also use querySelector with vanilla
document.querySelector('#container div.cleanstate').className = "cleanstate";
What if if you want to keep one or more than one classes and want classes except these. These solution would not work where you don't want to remove all classes add that perticular class again.
Using attr and removeClass() resets all classes in first instance and then attach that perticular class again. If you using some animation on classes which are being reset again, it will fail.
If you want to simply remove all classes except some class then this is for you.
My solution is for: removeAllExceptThese
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
$.fn.removeClassesExceptThese = function(classList) {
/* pass mutliple class name in array like ["first", "second"] */
var $elem = $(this);
if($elem.length > 0) {
var existingClassList = $elem.attr("class").split(' ');
var classListToRemove = existingClassList.diff(classList);
$elem
.removeClass(classListToRemove.join(" "))
.addClass(classList.join(" "));
}
return $elem;
};
This will not reset all classes, it will remove only necessary.
I needed it in my project where I needed to remove only not matching classes.
You can use it $(".third").removeClassesExceptThese(["first", "second"]);

Categories