jQuery: Getting "secondary" class - javascript

I'm using jQuery to loop through some elements in a document. These elements are of type <tr> with class .input-row. Some of the elements can also have a secondary class (for example .input-area).
I use $(".input-row").each() to loop through the elements, but how can I determine if the $(this)-element has a "secondary" class and if so, get the name of this?

$(".input-row").each(function(){
$.each($(this).attr('class').split(/\s+/), function(i, v){
if(v !== 'input-row'){
alert(v);
}
});
});

You can get the list of all classes using attr, and you could simply get rid of the the class you used to select the elements:
$(".input-row").each(function() {
var allClasses = $(this).attr("class"),
otherClasses = allClasses.replace("input-row", "");
});
If the element has more than two classes, then you will be left with a list of the other classes. To separate them, you could split on the spaces.

You can get all the classes on the element and then remove the one you know exists('input-row'), then you will be left with any other classes on that element.
$('.input-row').each(function() {
var classes = $.trim($(this).attr('class').replace('input-row', ''));
if (classes.length > 1) {
alert(classes) // Names of all of the remaining classes
}
}
If you want to get them individually, you can do classes.split(' ') to get an array.

I prefer a declarative approach. You know which classes there can be, so write cases for them:
$(".input-row.input-area").each( /* ... */ );
$(".input-row.input-field").each( /* ... */ );
If you for some reason don't know the class name, you can extract it along the lines of:
$(".input-row").each(function () {
var myClasses = this.className.split(" ");
$.each(myClasses, function (i, className) {
if (className != 'input-row') {
alert(className);
}
});
});

I'd go for this
var otherClasses = $('.input-row').attr('class').split(' ');
otherClasses.splice($.inArray("input-row", otherClasses),1);
Simply doing this
var otherClasses = $('.input-row').attr('class').replace('input-row', '').split(' ');
Will give you an extra string in the array with an empty value in it, because of the space behind "input-row"

You could also do something like this to detect the number of classes:
var nc = $('#myId').attr('class').split(' ').length;
Then if nc is greater than 1:
$('#myID').attr('class').split(' ')[1]
should return the 'secondary' class
See a fiddle

Related

How to get postid from the body class wordpress [duplicate]

There are several divs on my page with classes my_widget-2, my_widget-8, etc.
What JavaScript or jQuery code can I use to get the number "2" (ie. the number that appends the first matching widget)?
Note: If I were to write this question again, I would change the order of these class names and ask for a way to get "8" in order to avoid giving the impression that I want the smaller number.
$( "[class*='my_widget']" ).each ( function () {
var elClasses = $( this ).attr ( 'class' ).split ( ' ' );
for ( var index in elClasses ) {
if ( elClasses[index].match ( /^my_widget-\d+$/ ) ) {
var classNum = elClasses[index].split ( '-' )[1];
alert ( classNum );
break;
}
}
} );
Use the "attributeContains" selector to get all elements that have a class my_widget-*, and then loop trough all the classes the element has searching for you class. Once you find it, extract the number part.
This should do the trick:
$("[class^='my_widget']").each(function() {
var classParts = $(this).attr('class').split('-');
var number = classParts.pop();
});
Please note that it will only work if there is a singular class, otherwise you'd get something like 8 otherclass as a result.
Basic JS approach:
<div id="x" class="widget-2 lang-日本語">foo</div>
function Element_getClassArgument(el, name) {
var classes= el.className.split(' ');
var prefix= name+'-';
for (var i= classes.length; i-->0;)
if (classes[i].substring(0, prefix.length)==prefix)
return classes[i].substring(prefix.length);
return null;
}
Element_getClassArgument(document.getElementById('x'), 'widget'); // 2
If you wanted to include whitespace characters, or a hyphen in a name, you'd have to introduce an encoding scheme of some sort, for example encodeURIComponent. But often you can get away without that.
Wrapping in something with $ in the name is left as an exercise for the reader. :-)
If you want to get the DIV elements with a class my_widget-2, use this selector:
$("div.my_widget-2")
But if you want to get all DIV elements with a class of the form my_widget-N where N is an arbitrary number, try this:
$("div[class]").each(function() {
var matches = this.className.match(/(?:^|\s+)my_widget-(\d+)(?:\s+|$)/g);
if (matches !== null) {
alert(matches);
}
})
Try
element.attr('class').match(/my_widget-(\d+)/)[1]
It should return the column number as a string so just run parseInt() on it

JQuery get the rest of the element's class name that starts with string "whatever-"

I have js that caches classes that's name starts with "whatever-",
$('[class^="whatever-"], [class*=" whatever-"]')
but what I want now to do is get the rest of the name, for example in case of "whatever-9" I want to get "9", I don't know how to do it, can you help me?
Try this
var check = "whatever-";         
$('[class^="whatever-"], [class*=" whatever-"]').each(function () {    
// Get array of class names   
var cls = $(this).attr('class').split(' ');       
for (var i = 0; i < cls.length; i++) {
// Iterate over the class and log it if it matches
if (cls[i].indexOf(check) > -1) {        
console.log(cls[i].slice(check.length, cls[i].length));
}       
}    
});
This should also work for the case when there is more than 1 class. There may be cleaner ways of doing this by using filter method and a bit of regex
Check Fiddle
A little cleaner using map
var check = "whatever-";
$('[class^="whatever-"], [class*=" whatever-"]').each(function () {
var className = this.className;
var cls = $.map(this.className.split(' '), function (val, i) {
if (val.indexOf(check) > -1) {
return val.slice(check.length, val.length)
}
});
console.log(cls.join(' '));
});
Map demo
Maybe there are better ways, but this works. Check the console.
DEMO
$('[class^="whatever-"], [class*=" whatever-"]').each(function () {
var classname = this.className;
var classsparts = classname.split('whatever-');
var result = classsparts[1]
console.log(result);
});
This is assuming you just have one class in the elements you are targeting with your selectors.
Or if you like a little regular expression I would use this because hey it's just one line.
$("*").filter(function(){ return /whatever-.+/.test( $(this).attr("class") ) } );

Efficient way of hiding elements with certain classes $.each, for, etc

I have an array populated with classes. I need to loop across this array and hide any elements with that particular class.
// Array of classes
// hide.length ~ 100
This is my current implemntation:
// Hide all elements with these class names
$.each(hide, function(key, filter_class){
$('li.'+filter_class, '.result_row_items').hide();
});
I believe this would be a more efficient (performance wise) way:
for(i=0;i<hide.length;i++){
$('li.'+hide[i], '.result_row_items').hide();
}
Would this be even better?
// Create string of class names
var classes = '';
for(i=0;i<hide.length;i++){
classes += 'li.'+ hide[i] + ', '
}
// Remove trailing comma and space
classes = classes.substring(0, classes.length - 2);
$(classes, '.result_row_items').hide();
How about something like that?
$("li." + hide.join(",li."), ".result_row_items").hide();
DEMO: http://jsfiddle.net/B9fXP/
Maybe something like this?
$(hide).filter('.class').hide();
or
for (var i = 0; class = classes[i++];) {
$('li.'+ class).hide();
}

How to remove .class1, .class2, ... or classN?

we have this classnames
.lightbox620
.lightbox400
..
.lightbox200
That we apply to the body page and it determines its width...
so i need to remove this class,
how can i $('body').removeClass('ligbox{any}') ???
If that's the only class that you set to <body>, then remove all the classes
$("body").removeClass();
// or
document.body.className = "";
If not, go the plain DOM way, use a regular expression to strip the class name out of the string.
document.body.className = document.body.className.replace(/\blightbox\d+/, "");
The jQuery way is a bit more complicated here:
$("body").removeClass(function (index, oldClass) {
var matches = oldClass.match(/\blightbox\d+/) || [];
return matches[0];
});

Get class list for element with jQuery

Is there a way in jQuery to loop through or assign to an array all of the classes that are assigned to an element?
ex.
<div class="Lorem ipsum dolor_spec sit amet">Hello World!</div>
I will be looking for a "special" class as in "dolor_spec" above. I know that I could use hasClass() but the actual class name may not necessarily be known at the time.
You can use document.getElementById('divId').className.split(/\s+/); to get you an array of class names.
Then you can iterate and find the one you want.
var classList = document.getElementById('divId').className.split(/\s+/);
for (var i = 0; i < classList.length; i++) {
if (classList[i] === 'someClass') {
//do something
}
}
jQuery does not really help you here...
var classList = $('#divId').attr('class').split(/\s+/);
$.each(classList, function(index, item) {
if (item === 'someClass') {
//do something
}
});
Why has no one simply listed.
$(element).attr("class").split(/\s+/);
EDIT: Split on /\s+/ instead of ' ' to fix #MarkAmery's objection. (Thanks #YashaOlatoto.)
On supporting browsers, you can use DOM elements' classList property.
$(element)[0].classList
It is an array-like object listing all of the classes the element has.
If you need to support old browser versions that don't support the classList property, the linked MDN page also includes a shim for it - although even the shim won't work on Internet Explorer versions below IE 8.
Here is a jQuery plugin which will return an array of all the classes the matched element(s) have
;!(function ($) {
$.fn.classes = function (callback) {
var classes = [];
$.each(this, function (i, v) {
var splitClassName = v.className.split(/\s+/);
for (var j = 0; j < splitClassName.length; j++) {
var className = splitClassName[j];
if (-1 === classes.indexOf(className)) {
classes.push(className);
}
}
});
if ('function' === typeof callback) {
for (var i in classes) {
callback(classes[i]);
}
}
return classes;
};
})(jQuery);
Use it like
$('div').classes();
In your case returns
["Lorem", "ipsum", "dolor_spec", "sit", "amet"]
You can also pass a function to the method to be called on each class
$('div').classes(
function(c) {
// do something with each class
}
);
Here is a jsFiddle I set up to demonstrate and test http://jsfiddle.net/GD8Qn/8/
Minified Javascript
;!function(e){e.fn.classes=function(t){var n=[];e.each(this,function(e,t){var r=t.className.split(/\s+/);for(var i in r){var s=r[i];if(-1===n.indexOf(s)){n.push(s)}}});if("function"===typeof t){for(var r in n){t(n[r])}}return n}}(jQuery);
You should try this one:
$("selector").prop("classList")
It returns a list of all current classes of the element.
var classList = $(element).attr('class').split(/\s+/);
$(classList).each(function(index){
//do something
});
$('div').attr('class').split(' ').each(function(cls){ console.log(cls);})
Update:
As #Ryan Leonard pointed out correctly, my answer doesn't really fix the point I made my self... You need to both trim and remove double spaces with (for example) string.replace(/ +/g, " ").. Or you could split the el.className and then remove empty values with (for example) arr.filter(Boolean).
const classes = element.className.split(' ').filter(Boolean);
or more modern
const classes = element.classList;
Old:
With all the given answers, you should never forget to user .trim() (or $.trim())
Because classes gets added and removed, it can happen that there are multiple spaces between class string.. e.g. 'class1 class2 class3'..
This would turn into ['class1', 'class2','','','', 'class3']..
When you use trim, all multiple spaces get removed..
Might this can help you too. I have used this function to get classes of childern element..
function getClickClicked(){
var clickedElement=null;
var classes = null;<--- this is array
ELEMENT.on("click",function(e){//<-- where element can div,p span, or any id also a class
clickedElement = $(e.target);
classes = clickedElement.attr("class").split(" ");
for(var i = 0; i<classes.length;i++){
console.log(classes[i]);
}
e.preventDefault();
});
}
In your case you want doler_ipsum class u can do like this now calsses[2];.
Thanks for this - I was having a similar issue, as I'm trying to programatically relate objects will hierarchical class names, even though those names might not necessarily be known to my script.
In my script, I want an <a> tag to turn help text on/off by giving the <a> tag [some_class] plus the class of toggle, and then giving it's help text the class of [some_class]_toggle. This code is successfully finding the related elements using jQuery:
$("a.toggle").toggle(function(){toggleHelp($(this), false);}, function(){toggleHelp($(this), true);});
function toggleHelp(obj, mode){
var classList = obj.attr('class').split(/\s+/);
$.each( classList, function(index, item){
if (item.indexOf("_toggle") > 0) {
var targetClass = "." + item.replace("_toggle", "");
if(mode===false){$(targetClass).removeClass("off");}
else{$(targetClass).addClass("off");}
}
});
}
Try This. This will get you the names of all the classes from all the elements of document.
$(document).ready(function() {
var currentHtml="";
$('*').each(function() {
if ($(this).hasClass('') === false) {
var class_name = $(this).attr('class');
if (class_name.match(/\s/g)){
var newClasses= class_name.split(' ');
for (var i = 0; i <= newClasses.length - 1; i++) {
if (currentHtml.indexOf(newClasses[i]) <0) {
currentHtml += "."+newClasses[i]+"<br>{<br><br>}<br>"
}
}
}
else
{
if (currentHtml.indexOf(class_name) <0) {
currentHtml += "."+class_name+"<br>{<br><br>}<br>"
}
}
}
else
{
console.log("none");
}
});
$("#Test").html(currentHtml);
});
Here is the working example: https://jsfiddle.net/raju_sumit/2xu1ujoy/3/
For getting the list of classes applied to element we can use
$('#elementID').prop('classList')
For adding or removing any classes we can follow as below.
$('#elementID').prop('classList').add('yourClassName')
$('#elementID').prop('classList').remove('yourClassName')
And for simply checking if the class is present or not we can use hasClass
I had a similar issue, for an element of type image. I needed to check whether the element was of a certain class. First I tried with:
$('<img>').hasClass("nameOfMyClass");
but I got a nice "this function is not available for this element".
Then I inspected my element on the DOM explorer and I saw a very nice attribute that I could use: className. It contained the names of all the classes of my element separated by blank spaces.
$('img').className // it contains "class1 class2 class3"
Once you get this, just split the string as usual.
In my case this worked:
var listOfClassesOfMyElement= $('img').className.split(" ");
I am assuming this would work with other kinds of elements (besides img).
Hope it helps.
javascript provides a classList attribute for a node element in dom. Simply using
element.classList
will return a object of form
DOMTokenList {0: "class1", 1: "class2", 2: "class3", length: 3, item: function, contains: function, add: function, remove: function…}
The object has functions like contains, add, remove which you can use
A bit late, but using the extend() function lets you call "hasClass()" on any element, e.g.:
var hasClass = $('#divId').hasClass('someClass');
(function($) {
$.extend({
hasClass: new function(className) {
var classAttr = $J(this).attr('class');
if (classAttr != null && classAttr != undefined) {
var classList = classAttr.split(/\s+/);
for(var ix = 0, len = classList.length;ix < len;ix++) {
if (className === classList[ix]) {
return true;
}
}
}
return false;
}
}); })(jQuery);
The question is what Jquery is designed to do.
$('.dolor_spec').each(function(){ //do stuff
And why has no one given .find() as an answer?
$('div').find('.dolor_spec').each(function(){
..
});
There is also classList for non-IE browsers:
if element.classList.contains("dolor_spec") { //do stuff

Categories

Resources