CSS Class, Attribute, Property and jQuery

In this short post, I will show you how to add/remove attributes or properties to DOM elements and how to add/remove CSS classes from DOM elements using jQuery. Also, how attribute and properties are different in jQuery.

Before jQuery 1.6 there was no concept of property. Everything was treated as attributes. But now you must be wondering about how attribute and property are different in jQuery. Find out answer at below post,

Properties:

Add Property: The general syntax to add attribute to one or set of DOM elements

$("selector").prop("propertyname","value");

Add Multiple Properties: You can also add multiple properties together using prop().

$("selector").prop({property1: "value", property2: "value"})

Remove Property:

$("selector").removeProp("PropertyName");

 Note: prop and removeProp are available with jQuery 1.6 and its higher version.  

Attributes:

Add Attribute: The general syntax to add attribute to one or set of DOM elements

$("selector").attr("attributeName","value");

Add Multiple Attributes: You can also add multiple attribute together using attr().

$("selector").attr({attribute1: "value", attribute2: "value"})

Remove Attribute:

$("selector").removeAttr("attributeName");

CSS Classes:

Add CSS Class: The general syntax to add css class to one or set of DOM elements

$("selector").addClass("classname");

Add Multiple Classes: You can also add multiple CSS classes together using addClass().

$("selector").addClass('class1 class2');

Remove CSS Class:

$("selector").removeClass("classname");

Remove All CSS Class: To remove all associated CSS classes from element, then don't pass the class name while making a call to removeClass() method.

$("selector").removeClass();

Element has the cssClass associated with it:

$("selector").hasClass("classname");

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...