how to get one class from multiple classes in javascript - javascript

let check1 = document.querySelectorAll('.container input');
check1.forEach((elem)=>{
elem.addEventListener('click',()=>{
let boxes = document.querySelectorAll('.boxes');
boxes.forEach((ele)=>{
let boxesId = ele.getAttribute("class");
console.log(boxesId) //now there are three classes shown (boxes karat size)how to get size class
})
})
})
i am trying to get one class from multiple classes in javascript

Instead of using
ele.getAttribute("class");
Use the classList property.
let boxesId = ele.classList[2];
classList will return a list of all the classes. See documantation

Why you wanna do this? Sorry i can't understand.
But if you wann check if a element have a clas you can use the method includes.
element.classList.contains(className)

Related

Getting all classes from one element and adding them to another element in vanilla JavaScript

I'm trying to get all classes from one element, then add them to another element created dynamically. I was originally stuck on how to do this, but as I was typing out this question, I worked out a solution. However, it seems a bit verbose. Is there a way to do this same thing more efficiently, i.e. with fewer lines of code?
let classes = this.nextElementSibling.classList; // get classes from target element
classes += ''; // convert classlist object to string
let class_array = classes.split(' '); // convert string to array
const my_div = document.createElement('div'); // create a new div
for(i=0; i<class_array.length; i++) { // loop through array and add classes to the div
my_div.classList.add(class_array[i]);
}
Thanks in advance.
The className will give you a space-separated string of class names an element has. Just use that.
const my_div = document.createElement('div');
my_div.className = this.nextElementSibling.className;

Javascript - read all classes from an element with a unique class

I want to find with Javascript an element by class name. This class is unique. I try to do this with
var element = document.getElementByClassName('uniqueclass')
This element have two classes (uniqueclass and element-x). I want to get the other class and work with this class as String. I tried this with various functions (classname.split, ...), but I don't find a solution.
Can anybody help me? Thanks!
You can fetch the node, retrieve the classList of the node and filter them by your term:
var uniqueClassName = 'unique'; // What is your unique className?
var element = document.querySelector('.' + uniqueClassName); // Fetch the element
var filterClassList = function (class) {
return class !== uniqueClassName; // Differs the className from the unique one?
};
var classList = element.classList.filter(filterClassList); // Filter the classList via filter function
You are doing it in right way.
Few changes
element = document.getElementsByClassName('uniqueclass')[0];
It is Elements not Element and it return a HTML Collection. Since this class name is unique, use index [0].
To get other classses of this element,
class = element.getAttribute('class');
Now class contains "uniqueclass element-x"

How to use jquery to get one of the class name attribute of an html element which has multiple class names assigned [duplicate]

This question already has answers here:
jQuery - get the first class only from a element
(3 answers)
Closed 9 years ago.
For example:
<div class="home current">home</div>
When I use $(this).attr("class"), it simply returns "home current".
I want to get the "home" attribute only. How can I achieve this?
If you know the class name and want to check if an element has it, you can use .hasClass()
// will return true if the element has that class applied to it
$(elem).hasClass('home');
On the other hand, if you want each class applied to an element separately, you can split by space and iterate:
var classes = $(elem).attr('class').split(' ');
for(var i=0; i<classes.length; i++) {
classes[i]; // each class name
}
The class attribute returns the space delimitered list of css classes assigned to the element, to convert this into an array use the split method on the string, and to retrieve the first one, use the [0] indexer, as in:
var firstClass = $(this).attr('class').split(' ')[0]
var allClass= $(this).attr("class");
var class = allClass.replace("current", "");
this will work if you only have "current" as an additional class
Is there a specific reason that you need to pull the class list. If you know the class you are looking for and just need to check if the object has the class home, you could do this:
$(this).hasClass("home");
Otherwise, you could just split the result and check for whatever class you need.
var classAttr = $(this).attr("class");
var classes = classAttr.split(" ");
It seems you need the primary class of the element.
var primaryClass= $(this).attr('class').split(' ')[0].
Remember this line may cause exception if no class applied,while the time you using it.

How can I replace a class with another using jQuery?

What jquery can I use to change the class that's used in the following from indent_1 to indent_2 or indent_4 to indent_2? I know about remove class but how can I do that when the classes are names that vary?
<div class="rep_td0 indent_1" id="title_1">Menu two</div>
or
<div class="rep_td0 indent_4" id="title_1">Menu two</div>
Since you haven't been very specific about exactly what class you want to change to another and you've said you want to deal with the case where you don't know exactly what the class is, here are some ideas:
You can find all objects that have a class that starts with "indent_" with this selector:
$('[className^="indent_"]')
If you wanted to examine the class on each one of those objects, you could iterate over that jQuery object with .each() and decide what to do with each object or you could use removeClass() with a custom function and examine the class name and decide what to do with it.
If you just wanted to change all indent class names to indent_2, then you could use this:
$('[className^="indent_"]').removeClass("indent_1 indent_3 indent_4").addClass("indent_2");
or, using a custom function that can examine the class name with a regex:
$('[className^="indent_"]').removeClass(function(index, name) {
var match = name.match(/\bindent_\d+\b/);
if (match) {
return(match[0]);
} else {
return("");
}
}).addClass("indent_2");
Or, if all you want to do is find the object with id="title_1" and fix it's classname, you can do so like this:
var o = document.getElementById("title_1");
o.className = o.className.replace(/\bindent_\d+\b/, "indent_2");
You can see this last one work here: http://jsfiddle.net/jfriend00/tF8Lw/
If you're trying to make this into a function that could take different numbers, you could use this:
function changeIndentClass(id, indentNum) {
var item = document.getElementById(id);
item.className = item.className(/\bindent_\d+\b/, "indent_" + indentNum);
}
try this code,
$("#title_1").removeClass("indent_1").addClass("indent_2");
if you not sure which is available, try this
$("#title_1").removeClass("indent_1").removeClass("indent_4").addClass("indent_2");
Updated:
$("#title_1").removeClass(function() {
var match = $(this).attr('class').match(/\bindent_\d+\b/);
if (match) {
return (match[0]);
} else {
return ("");
}
}).addClass("indent_2");
Try below :
$('#title_1').removeClass('indent_1').addClass('indent_2');
Here, the indent_1 classes will be replaced with indent_2.
Maybe this?: Remove all classes that begin with a certain string
That answers how to replace a classname on a jQuery element that has a specific prefix, such as 'indent_'.
While that answer doesn't specifically address replacement, you can achieve that by altering one of their answers slightly:
$("selector").className = $("selector").className.replace(/\bindent.*?\b/g, 'indent_2');
Or similar...
First things first...If you have multiple elements on your page with the exact same ID you're going to have problems selecting them by ID. Some browsers won't work at all while others may return just the first element that matches.
So you'll have to clean up the ID thing first.
You can use the starts with selector to find all the classes that match your class name patter and then decide if you want to switch them or not:
$('[class^="indent_"]').each(function() {
var me = $(this);
if(me.hasClass("indent_1").removeClass("indent_1").addClass("indent_2");
});

How can I remove all CSS classes using jQuery/JavaScript?

Instead of individually calling $("#item").removeClass() for every single class an element might have, is there a single function which can be called which removes all CSS classes from the given element?
Both jQuery and raw JavaScript will work.
$("#item").removeClass();
Calling removeClass with no parameters will remove all of the item's classes.
You can also use (but it is not necessarily recommended. The correct way is the one above):
$("#item").removeAttr('class');
$("#item").attr('class', '');
$('#item')[0].className = '';
If you didn't have jQuery, then this would be pretty much your only option:
document.getElementById('item').className = '';
Hang on, doesn't removeClass() default to removing all classes if nothing specific is specified? So
$("#item").removeClass();
will do it on its own...
Just set the className attribute of the real DOM element to '' (nothing).
$('#item')[0].className = ''; // the real DOM element is at [0]
Other people have said that just calling removeClass works - I tested this with the Google jQuery Playground: http://savedbythegoog.appspot.com/?id=ag5zYXZlZGJ5dGhlZ29vZ3ISCxIJU2F2ZWRDb2RlGIS61gEM ... and it works. So you can also do it this way:
$("#item").removeClass();
Of course.
$('#item')[0].className = '';
// or
document.getElementById('item').className = '';
Remove specific classes:
$('.class').removeClass('class');
Say if element has class="class another-class".
The shortest method
$('#item').removeAttr('class').attr('class', '');
You can just try:
$(document).ready(function() {
$('body').find('#item').removeClass();
});
If you have to access that element without a class name, for example you have to add a new class name, you can do this:
$(document).ready(function() {
$('body').find('#item').removeClass().addClass('class-name');
});
I use that function in my project to remove and add classes in an HTML builder.
I like using native JavaScript to do this, believe it or not!
solution 1: className
Remove all class of all items
const items = document.querySelectorAll('item');
for (let i = 0; i < items.length; i++) {
items[i].className = '';
}
Only remove all class of the first item
const item1 = document.querySelector('item');
item1.className = '';
solution 2: classList
// remove all class of all items
const items = [...document.querySelectorAll('.item')];
for (const item of items) {
item.classList.value = '';
}
// remove all class of the first item
const items = [...document.querySelectorAll('.item')];
for (const [i, item] of items.entries()) {
if(i === 0) {
item.classList.value = '';
}
}
// or
const item = document.querySelector('.item');
item.classList.value = '';
jQuery ways (not recommended)
$("#item").removeClass();
$("#item").removeClass("class1 ... classn");
refs
https://developer.mozilla.org/en-US/docs/Web/API/Element/className
https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
$('#elm').removeAttr('class');
Attribute "class" will no longer be present in "elm".
Since not all versions of jQuery are created equal, you may run into the same issue I did, which means calling $("#item").removeClass(); does not actually remove the class (probably a bug).
A more reliable method is to simply use raw JavaScript and remove the class attribute altogether.
document.getElementById("item").removeAttribute("class");
Let's use this example. Maybe you want the user of your website to know a field is valid or it needs attention by changing the background color of the field. If the user hits reset then your code should only reset the fields that have data and not bother to loop through every other field on your page.
This jQuery filter will remove the class "highlightCriteria" only for
the input or select fields that have this class.
$form.find('input,select').filter(function () {
if((!!this.value) && (!!this.name)) {
$("#"+this.id).removeClass("highlightCriteria");
}
});
Try with removeClass.
For instance:
var nameClass=document.getElementsByClassName("clase1");
console.log("after", nameClass[0]);
$(".clase1").removeClass();
var nameClass=document.getElementsByClassName("clase1");
console.log("before", nameClass[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clase1">I am a Div with class="clase1"</div>
I had a similar issue. In my case, on disabled elements was applied that aspNetDisabled class and all disabled controls had wrong colors. So, I used jQuery to remove this class on every element/control I want and everything works and looks great now.
This is my code for removing aspNetDisabled class:
$(document).ready(function () {
$("span").removeClass("aspNetDisabled");
$("select").removeClass("aspNetDisabled");
$("input").removeClass("aspNetDisabled");
});

Categories