Web Designing Tutorials

How to Get and Set Element Attributes using jQuery

Google+ Pinterest LinkedIn Tumblr
Some of the simplest and most common, operations on jQuery objects are those that get or set the value of HTML attributes, CSS styles, element content, or element geometry. In this post, I am going to describe the methods to get and set element attributes using jQuery.

How to Get and Set HTML Attributes using jQuery

You can get or set HTML element attributes using the attr() method in jQuery. The attr() method handles browser incompatibilities and special cases. It allows you to use either HTML element attributes names or their JavaScript property equivalents.

Read Also: How to Use jQuery With HTML?

Here are some examples of uses of attr() method for getting or setting HTML attributes.

$("form").attr("action");  
// It gets the action attribute from the first form.
$("#icon").attr("src", "icon.gif");  
// It sets the src attributes for image with id icon.
$("a").attr("target", "_blank");  
// It set the target attributes for all links to load in new windows 
$("a").attr("target", function(){
 if(this.host==location.host) return "_self"
 else return "_blank";
});

This function sets the attribute of all external links load in new windows and internal links load in the same window.

There is another method related to attr() is removeAttr(), which is a related function that completely removes an attribute from all selected elements.

Here an example of uses of removeAttr() method for removing HTML attributes.

$("a").removeAttr("target");

It removes the target attribute of the link and makes all links load in the same window.

How to Get and Set CSS Attributes using jQuery

The css() method is very much like attr() method, but it works with the CSS styles of an element rather than the HTML attributes of the element.

When querying style values, css() returns the current style of the element and the returned value may come from the style attribute or from a style-sheet.

For example, the following code shows how to get and set the CSS attributes using the attr() method using jQuery.

$("h1").css("font-weight"); 
// It gets font weight of first <h1>
$("h1").css("font-variant", "smallcaps"); 
// It sets font-variant property of <h1> to smallcaps.
$("h1").css({backgroundColor:"black",textColor:"white",
 fontVariant:"small-caps", padding: "10px 2px 4px 20px", 
 border:"dotted black 4px"});   
// It sets multiple styles at once for <h1>

Read Also: How to Create Animated Visual Effects Using jQuery

Adding, Removing and Toggling CSS Classes

Since jQuery defines convenience methods for working with the class attribute. The addClass() and removeClass() methods add and remove classes from the selected elements. In addition, the toogleClass() method adds classes to elements that don’t already have them and removes classes from those that do. hasClass() tests for the presence of a specified class.

Here are are some examples for adding CSS classes, removing CSS classes, toggling CSS classes and testing CSS classes.

Adding CSS Classes

$("h1").addClass("hilite");  
// It adds a class to all <h1> elements
$("h1+p").addClass("hilite first"); 
// It adds two classes to elements after <h1>
$("section").addClass(function(n){return "scetion"+n;}); 
// It passes a function to add a custom class to each matched element

Removing CSS classes

$("p").removeClass("hilite");  
// It removes a class from all p elements
$("p").removeClass("hilite first"); 
// It removes two classes from <p> elements
$("section").removeClass(function(n){return "scetion"+n;}); 
// It passes a function to remove a custom class to each matched element

Toggling CSS Classes

$("tr:odd").toggleClass("oddrow"); 
// It adds the class if it is not there or remove if it is.
$("h1").toggleClass("big bold");   
// It toggles two classes at once. 
$("h1").toggleClass(function(n){
return "big bold h1-" +n; });  
// It toggles a computed class or classes.
$("h1").toggleClass("hilite", true); 
// It works like addclass
$("h1").toggleClass("hilite", false); 
// It works like removeclass

Testing CSS Classes

$("p").hasClass("first")  
// It tests any p element have class first
$("#lead").is("first") 
// It test any element with id lead have class first

The hasClass() method is less flexible than addclass(), removeClass, and toggleClass(). So, the hasClass() method works for only a single class name and does not support function arguments. In addition, it returns true if any of the selected elements has the specified CSS class and returns false if none of them do. The is() method is more flexible and can be used for the same purpose.

Read Also: Create Show/Hide Effect in Image SlideShow Using JQuery

How to Get and Set HTML Form Values using jQuery

For setting and querying the value attribute of the HTML form elements val() method is used and it is also used for querying and setting the selection state of checkboxes, radio buttons, and select elements. Here are some examples of getting and setting HTML form values using val() method.

$("#firstname").val()  
// It gets value from the firstname text field.
$("select #extras").val() 
// It gets array of values from <select multiple< from element. 
$("input:radio[name=ship]:checked").val() 
// It gets value of checked radio button.

How to Get and Set Element Content

The text() and html() methods query and set the plain-text or HTML content of an element or elements. When invoked with no arguments, text() returns the plain text content of all descendant text nodes of all matched elements. This works even in browsers that do not support the textContent or innerText properties.Here are some examples of getting and setting element content using text() and html() method.

var title=$("head title").text() //It gets document title
var headline=$("h1").html() 
//It gets the html of first <h1> element
$("h1").text(function(n,current){
 return "$" + (n+1) + ": "+current }); 
// It gives section number for each headings

How to Get and Set Element Geometry

To query or set the position of an element, we should use the offset() method. So, this method measures positions relative to the document and returns them in the form of an object with left and top properties that hold the X and Y coordinates. If you pass an object with these properties to the method, it sets the position you specify. Here are some examples of getting and setting element geometry using offset() method.

var elt=$("#sprite");
var position=elt.offset(); 
// It gets the current position of an elememt
position.top +=100;
// It changes its Y coordinate 100px.
elt.offset(position);

How to Get and Set Element Data

Since, jQuery defines a getter or setter method named data() that sets or queries data associated with any document element or with the Document or window objects. You can also use removeData() method to remove data from an element or elements. Here are some examples of getting and setting element data using data() method removing data using removeData() method.

$("div").data("x",1); 
//It sets some data "x" to div
$("div.nodata").removeData("x"); 
//It removes some data "x" from div with class nodata
var x=$("#mydiv").data("x"); 
//It query some data from element id "mydiv"

Read Next: How to Alter HTML Document Structure using jQuery?

Shuseel Baral is a web programmer and the founder of InfoTechSite has over 8 years of experience in software development, internet, SEO, blogging and marketing digital products and services is passionate about exceeding your expectations.

Write A Comment