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

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"

Related

how to get one class from multiple classes in 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)

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 Adding Element to DOM Syntax Troubles

Okay, so I searched and could not really find an answer for this. I am creating a Javascript function that will easily add an element to the specified element. Here is the syntax:
function add(element, to, idName, className) {
//creates new element for DOM
var newElement = document.createElement(element);
//sets ID attribute for element
var attrId = newElement.createAttribute('id');
attrId.value = idName;
//sets class attribute
var attrClass = newElement.createAttribute('class');
attrClass.value = className;
document.getElementById(to).appendChild(newElement);
}
Long story short, it doesn't work. Yes, my JS is linked fine to my HTML and I have already used many other functions in the same JS file, but this is the one I am having trouble on. I am sure there is some form of a syntax error but can't seem to find it.
P.S. This is my first time using JS to dynamically add a page element without changing innerHTML directly.
The problem is that the id and class are already defined in each element.
To access an element's id, just do element.id = id. As for the classes, there's a thing called element.classList, and if you want to add a class just type element.classList.add("class_name"), and to remove it type element.classList.remove("class_name").
The correct code now comes as:
function add(element, to, idName, className) {
//creates new element for DOM
var newElement = document.createElement(element);
//sets ID attribute for element
newElement.id = idName;
//sets class attribute
newElement.classList.add(className);
document.getElementById(to).appendChild(newElement);
}
check this documentation to understand more about classLists
There's no reason to use .createAttribute() here. You're creating those attributes, but doing nothing to associate them with the element you're creating. Things are much simpler than that:
function add(element, to, idName, className) {
//creates new element for DOM
var newElement = document.createElement(element);
//sets ID attribute for element
newElement.id = id;
//sets class attribute
newElement.className = className;
document.getElementById(to).appendChild(newElement);
}
Note that you're probably going to want to work on the fact that you sometimes need more than just a tag name, id, and class. <input> elements are a good example — they require a "type" attribute (well, not really require, but an API like this would need to account for that.)

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.

jQuery selector stored in variable: How to Select specific elements by attribute value?

I know that I get an element(s) by attribute via, e.g.
$('.js_aBunchOfElements span[data-stuff="special"]');
Yet once I store the selector in a variable:
var bunch = $('.js_aBunchOfElements span');
I am confused how to search within bunch for my elements with the attribute data-stuff="special".
bunch.filter('[data-stuff=special]') should do it.
bunch.filter(function() {
return $(this).attr("data-stuff") == "special";
});

Categories