Get the App
SLTechnology News&Howtos  ›  Development  › 

How to add a class to an element in jquery

Shulou Source: shulou.com Published: 2022-06-01 04:54:39 11月17日 Update

This article mainly introduces "how to add a class to elements in jquery". In daily operation, I believe many people have doubts about how to add a class to elements in jquery. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how to add a class to elements in jquery". Next, please follow the editor to study!

Jquery adds a class to the element: 1, using the attr () method, syntax "$(selector) .attr (" class "," class name ")"; 2, using the addClass () method, syntax "$(selector) .addClass (" class name ")".

The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.

Add a class to the element in jquery

1. Use the attr () method

The attr () method sets or returns the property value of the selected element.

The working mode of the method is also different according to the different parameters of the method.

$(document) .ready (function () {$("button") .click (function () {$("p:first"). Attr ("class", "intro");}) .intro {font-size: 150%; color: red;} this is a title

This is a paragraph.

This is another paragraph.

Add a class name to the first P element

2. Use the addClass () method

The addClass () method adds one or more class names to the selected element.

This method does not remove the existing class attribute, but simply adds one or more class names to the class attribute.

Tip: if you need to add more than one class, separate the class names with spaces.

$(document) .ready (function () {$("button") .click (function () {$("p:first"). AddClass ("intro");}) .intro {font-size: 150%; color: pink;} this is a title

This is a paragraph.

This is another paragraph.

Add a class name to the first P element

At this point, the study on "how to add a class to an element in jquery" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Element method class name this is paragraph learning multiple attributes more title syntax help different practical next parameters differences tutorials articles methods Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi macOS Shulou Technology MariaDB NVidia