Javascript list css classes

Manipulating CSS Classes with classList — DOM

In this article, you will learn how to use the JavaScript classList property to work with the CSS classes of an element by either removing, adding, toggling, or checking if a class exists in an element. This is something we often use when building the frontend of web applications. Previously, almost everyone relied on jQuery to perform these kinds of DOM manipulations, but it never made sense importing a whole jQuery library just to perform little DOM manipulation.

What is the classList property?

The classList is a read-only property of an element that returns a collection of CSS classes and allows us to make use of some methods as well for managing and updating those classes. Example:
If we have a p tag element with class short-note and paragraph

 class="short-note paragraph" id="content">Lorem ipsum dolor sit amet, consectetur adipisicing el. 
let theClasses = document.querySelector('#content'); console.log(theClasses.classList); 
  • add() : Adds specified classes
  • remove() : Removes specified classes
  • contains() : Checks whether the specified class exists on the element
  • toggle() : toggles specified class

I will be explaining each of them with an example and then at the end of this article, you will see a codepen link to a simple sidebar project of which I made use of the classList property.

add()

To add one or more CSS classes to the class list of an element, you use the add() method of the classList .

Example:
The following code adds the show class to the class list of the div element with the id content :

let div = document.querySelector('#content'); div.classList.add('show'); 

we can also add multiple CSS classes to the class list of an element:

let div = document.querySelector('#content'); div.classList.add('show','remove','flow'); 

remove()

To remove one or more CSS classes from the class list of an element, you use the remove() method of the classList .

Example:
The following code removes the show class from the class list of the div element with the id content :

let div = document.querySelector('#content'); div.classList.remove('show'); 

we can also remove multiple CSS classes from the class list of an element:

let div = document.querySelector('#content'); div.classList.remove('show','remove','flow'); 

contains()

This method helps us know if a particular class is contained in our element. The contains() method returns true if the classList contains a specified class; otherwise false .

let div = document.querySelector('#content'); div.classList.contains('show'); // true 

toggle()

The toggle() method is a very cool method most frontend developers use from time to time as it saves you the whole stress of checking if a class exists then remove or otherwise. The toggle method helps us make use of just one line of code instead of about 5 lines of code.

Читайте также:  Сортировка методом прямого выбора питон

Simply, it checks if the class list of an element contains a specified class name, the toggle() method removes it. If the class list doesn’t contain the class name, the toggle() method adds it to the class list. This is mostly used for hamburger menus.

let div = document.querySelector('#content'); div.classList.toggle('visible'); 

There are other methods like:

  • index() : returns the class at a specified position in the list
  • length : returns the number of classes

Briefly, we have seen how we could make use of these methods to either add, remove, toggle, or check if a class exists in an element.

As I promised here is a simple sidebar project in which I used these classList methods to either hide the sidebar or show the navbar by wither adding or removing a CSS class.

As always, any questions or suggestions, please feel free to leave a response or tweet me 🤭! Be sure to connect with me on socials! 😎

Источник

Listing Known CSS Classes Using JavaScript

The thing, though, is that it includes all rules regardless of being class or tag or id or whatever..

You will need to explain in more detail what you want to happen for non class rules (or combined rules)

Is there a way to list all available css classes for a web page?

 for (let link of document.querySelectorAll("link, style")) try if (!link.sheet) console.warn("Warning:", "Property 'sheet' is not set on element", link) 
> else
for (let rule of link.sheet.rules) console.log(rule.selectorText)
>;
> catch (e) console.warn("Warning:", e.message, ". Try set crossorigin='anonymous' on element", link)
>
>;

or in the Chrome DevTool window (F12), find the «Elements», then «Styles», tab. On the right side of the «filter» text-box there is a «.cls» option. Click it and an «add new class» input should appear. Focus that input and hit Ctrl + Space. A pick list of all class styles in the current opened document should appear.

It looks something like this:

How to get all CSS classes of an element?

No need to use jQuery for it:

var classList = this.className.split(' ')

If you for some reason want to do it from a jQuery object, those two solutions work, too:

var classList = $(this)[0].className.split(' ')
var classList = $(this).prop('className').split(' ')

Of course you could switch to overkill development mode and write a jQuery plugin for it:

$.fn.allTheClasses = function() return this[0].className.split(' ');
>

Then $(this).allTheClasses() would give you an array containing the class names.

Читайте также:  Garry mod css контент

How to make list of all classes in the page using jQuery?

jQuery has an attribute selector — choose only elements which have class atribute 🙂
Then split class attribute string (for cases like class=»one two») and add them to array (dont forget to check if class is not empty or isnt already in the array. Use this.valueOf() for checking and saving the string 🙂

var classes = [];
$('[class]').each(function() $($(this).attr('class').split(' ')).each(function() <
if (this.length>0 && $.inArray(this.valueOf(), classes) === -1) classes.push(this.valueOf());
>
>);
>);
console.log("LIST START\n\n"+classes.join('\n')+"\n\nLIST END");

JSFiddle link : http://jsfiddle.net/MWJKL/

If you get a reference to an element through JavaScript you can generally only get CSS properties that have been set through inline CSS using the style-attribute of the element. Properties applied through CSS can not be read through the element as properties of that element.

You can however use window.getComputedStyle() within your loop to get the final computed CSS that has been applied to the element.

In your case it would be something like:

var toto = document.getElementsByClassName('toto');
if (toto) for (int i; i < toto.length; i++)
// Log the height of each element
console.log(getComputedStyle(toto[i], null).getPropertyValue("height"));
>
>

Notice that the browser-support is somewhat limited (IE9+).

How can you determine if a css class exists with Javascript?

This should be possible to do using the document.styleSheets[].rules[].selectorText and document.styleSheets[].imports[].rules[].selectorText properties. Refer to MDN documentation.

How do you read CSS rule values with JavaScript?

Adapted from here, building on scunliffe’s answer:

function getStyle(className) var cssText = ""; 
var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var x = 0; x < classes.length; x++) <
if (classes[x].selectorText == className) cssText += classes[x].cssText || classes[x].style.cssText;
>
>
return cssText;
>

alert(getStyle('.test'));

Applying a CSS class on click to a list item?

Adding an event listener to every single list item is considered to be bad practice. Instead you can use one click event to handle all your list items.

Instead do something like this

const songSelects = document.getElementById('set-1'); // This is your UL element

function changeColor(e) e.target.classList.add('song-selection');
>

songSelects.addEventListener('click', changeColor);

This example will add an event listener to your UL element which will capture every clicked on list item within the list. You can access the actual item that has been clicked on through the event object, specifically its target property. This will then add your class to the individual list item that was clicked.

Источник

JavaScript classList

Summary: in this tutorial, you will learn how to use the JavaScript classList property to work with the CSS classes of an element.

Introduction to JavaScript classList property

The classList is a read-only property of an element that returns a live collection of CSS classes:

const classes = element.classList;Code language: JavaScript (javascript)

The classList is a DOMTokenList object that represents the contents of the element’s class attribute.

Even though the classList is read-only, but you can manipulate the classes it contains using various methods.

JavaScript classList examples

Let’s take some examples of manipulating CSS classes of the element via the classList ‘s interface.

1) Get the CSS classes of an element

Suppose that you have a div element with two classes: main and red .

div id="content" class="main red">JavaScript classList div> Code language: HTML, XML (xml)

The following code displays the class list of the div element in the Console window:

let div = document.querySelector('#content'); for (let cssClass of div.classList) < console.log(cssClass); >Code language: JavaScript (javascript)
  • First, select the div element with the id content using the querySelector() method.
  • Then, iterate over the elements of the classList and show the classes in the Console window.

2) Add one or more classes to the class list of an element

To add one or more CSS classes to the class list of an element, you use the add() method of the classList .

For example, the following code adds the info class to the class list of the div element with the id content :

let div = document.querySelector('#content'); div.classList.add('info'); Code language: JavaScript (javascript)

The following example adds multiple CSS classes to the class list of an element:

let div = document.querySelector('#content'); div.classList.add('info','visible','block'); Code language: JavaScript (javascript)

3) Remove element’s classes

To remove a CSS class from the class list of an element, you use the remove() method:

let div = document.querySelector('#content'); div.classList.remove('visible');Code language: JavaScript (javascript)

Like the add() method, you can remove multiple classes once:

let div = document.querySelector('#content'); div.classList.remove('block','red');Code language: JavaScript (javascript)

4) Replace a class of an element

To replace an existing CSS class with a new one, you use the replace() method:

let div = document.querySelector('#content'); div.classList.replace('info','warning');Code language: JavaScript (javascript)

5) Check if an element has a specified class

To check if the element has a specified class, you use the contains() method:

let div = document.querySelector('#content'); div.classList.contains('warning'); // trueCode language: JavaScript (javascript)

The contains() method returns true if the classList contains a specified class; otherwise false .

6) Toggle a class

If the class list of an element contains a specified class name, the toggle() method removes it. If the class list doesn’t contain the class name, the toggle() method adds it to the class list.

The following example uses the toggle() method to toggle the visible class of an element with the id content :

let div = document.querySelector('#content'); div.classList.toggle('visible');Code language: JavaScript (javascript)

Summary

  • The element’s classList property returns the live collection of CSS classes of the element.
  • Use add() and remove() to add CSS classes to and remove CSS classes from the class list of an element.
  • Use replace() method to replace an existing class with a new one.
  • Use contains() method to check if the class list of an element contains a specified class.
  • Use the toggle() method to toggle a class.

Источник

Оцените статью