Jquery set HTML attributes CSS classes and HTML form values and element content and data

satinder singh / Updated : / 0 Comments

# 2- Element Get and Set-

How to set HTML attributes: CSS styles and classes,  HTML form values, and element content and data

Some of the simplest and most common operations on jQuery objects are to get or set the value of HTML attributes, CSS styles, element content here we learn those methods.

#2.1 –  Get and Set HTML Attributies:

The attr() method is the jQuery getter/setter for HTML attributes,
$("#BannerImg").attr("src", "icon.gif");     // Set the src attribute of element with id banner
$("a").attr("target", "_blank");   // Make all links load in new windows
$("#banner").attr({src:"banner.gif",          // Set 4 attributes at once


The  attr() is jQuery’s master attribute-setting function, and you can use it to set things other than normal HTML attributes. If you use the attr() method to set an attribute named “css”, “val”, “html”, “text”, “data”, “width”, “height”, or “offset”, jQuery invokes the method that has the same name as that attribute and passes whatever value you specified as the argument.

For example, calling attr("css", {backgroundColor:"gray"}) is the same as callingcss({backgroundColor:"gray"}) .
We’ll learn about css(), val(), html(), and other methods in later article.

#2.2 –  Get and Set CSS Attributes:

The  css() method is very much like the attr() method, but it works only with the CSS styles of an element ie sets or returns one or more style properties for the selected elements.

Sample Code:

$("h3").css("font-weight"); // Get font weight of 1st <h3>
$("h3").css("fontWeight"); // Camel case works, too
$("h3").css("font"); // ERROR: can’t query compound style
$("h3").css("font-variant","smallcaps"); // Set style on all <h1> tags 


Post Comment

Your email address will not be published. Required fields are marked *