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

/ / 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.

// Set the src attribute of element with id banner
$("#BannerImg").attr("src", "icon.gif");


// Make all links load in new windows
$("a").attr("target", "_blank");

// Set 4 attributes at once
$("#banner").attr({
    src: "banner.gif",
    alt: "Advertisement",
    width: 720,
    height: 64
});
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 
//*
  

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

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

0 Comments