Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use addClass

Shulou Source: shulou.com Published: 2022-06-01 03:30:16 10月12日 Update

This article mainly introduces the relevant knowledge of how to use addClass, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this article on how to use addClass. Let's take a look at it.

.addClass (className)

Description: adds the specified style class name for each matching element

ClassName

Type: String

One or more style names to be added to each matching element.

.addClass (function (index, currentClass))

Function (index, currentClass)

Type: Function ()

This function returns one or more style names to be added separated by spaces. The receive index parameter represents the index position of the element in the matching collection and the html parameter represents the original HTML content on the element. In the function, this points to the current element in the set of matching elements.

It is worth noting that this method does not replace a style class name. It simply adds a style class name to the element.

You can add multiple style class names separated by spaces to all matching elements at a time, like this:

$("p") .addClass ("myClass yourClass")

This method is usually used with .removeClass () to switch the style of an element, like this:

RemoveClass ("myClass noClass") .addClass ("yourClass")

Here, the myClass and noClass style names are removed from all paragraphs, and then yourClass is added.

Since jQuery 1.4, the .addClass () method allows us to pass a function that sets the style class name.

$("ul li:last") .addClass (function (index) {

Return "item-" + index

})

Given an unordered list of two elements, this example will add the "item-1" style to the last element.

Example:

Example: add the 'selected' style to the matching elements.

P {margin: 8px; font-size:16px;}

.selected {color:blue;}

.highlight {background:yellow;}

Hello

And

Goodbye

$("p") .last () .addClass ("selected")

This is the end of the article on "how to use addClass". Thank you for reading! I believe you all have a certain understanding of the knowledge of "how to use addClass". If you want to learn more knowledge, you are welcome to follow the industry information channel.

Tags: Element style class name content function method knowledge example parameter multiple more space article type value location just point easy to operate article Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Huawei Shulou Technology Shulou Information Xiaomi