How does jquery determine whether an element has a specified class name?
This article mainly introduces the relevant knowledge of "jquery how to judge whether an element has a specified class name". The editor shows you the operation process through an actual case. The method of operation is simple and fast, and it is practical. I hope this article "jquery how to determine whether an element has a specified class name" can help you solve the problem.
Judgment method: 1, use hasClass () to check whether the element contains the specified class name, syntax "element object .hasClass (" class name ")"; 2, use attr () to get the value of the class attribute, determine whether the attribute value is equal to the specified class name, syntax "element object .attr (" class ") =" class name ".
The operating environment of this tutorial: windows7 system, jquery1.10.2 version, Dell G3 computer.
Jquery has two ways to determine whether an element contains a specified class name:
Using hasClass ()
Using attr ()
Method 1: using hasClass ()
The hasClass () method checks whether the selected element contains the specified class name. If the selected element contains the specified class, the method returns "true".
$(document) .ready (function () {$("button") .click (function () {if ($("p"). HasClass ("intro")) {console.log ("with a specified class name") } else {console.log ("no class name specified");}}) }); .intro {font-size: 120%; color: red } this is a paragraph title. This is a paragraph.
This is another paragraph.
Whether there is a "intro" class in the p element
Method 2: using attr ()
Attr () can get the value of the class attribute, which is the class name
You only need to determine whether the property value is equal to the specified class name.
$(document) .ready (function () {$("button") .click (function () {if ($("p"). Attr ("class") = = "intro") {console.log ("with specified class name") } else {console.log ("no class name specified");}}) }); .intro {font-size: 120%; color: red } this is a paragraph title. This is a paragraph.
This is another paragraph.
Whether there is a "intro" class in the p element
This is the end of the content about "how jquery determines whether an element has a specified class name". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.