Just jQuery The Core UI - Modifying The DOM
Written by Ian Elliot   
Thursday, 16 June 2022
Article Index
Just jQuery The Core UI - Modifying The DOM
Attributes
Content

jQuery Attributes

Now that you know how HTML and the DOM distinguish between attributes and properties you can guess that jQuery has functions to help out with both. Of course, you can always do what we did in the previous section and work with the raw DOM object and its functions, but the jQuery versions are slightly easier and more powerful. 

The method:

attr("attribute")

returns the value of the specified attribute of the first element in the set of selected elements. 

You can also set attributes of objects using jQuery methods. For example, to set the id of a div you might use: 

$("div").attr("id","myDiv");

which sets the id attributes to myDiv.

You can set any attribute using the same approach. 

The main complication is that the attr method will set the attribute on all of the elements wrapped by the jQuery object. This is clearly not a good idea if you are setting the id attribute!

If the attribute already exists on an element then its value is changed. If it doesn't already exist then it is added to the attributes property of the DOM element. If you try to set an attribute to null then it is removed from attributes. 

As well as the attr method there is also the removeAttr method that removes the attribute from the attributes property. You can also set multiple attributes by passing an object as a property value list. For example:

$("div").attr({"id":"myDiv2","class":"myClass2"});

sets both the id and the class property on every object in the results set. 

You can also compute the new value of an attribute by passing a function as the second argument. The function is called for each element with the first parameter set to the index and the second to the value of the attribute. The return value of the function is the new value of the attribute. If the function returns nothing or undefined the attribute is removed. For example, to give each div in a document a unique id of the form div0, div1 and so on:

$("div").attr("id",function(i,val){return "div"+i;});

jQuery Properties

Each of the attribute methods has a corresponding property method as the following examples show:

prop("propertyname")

returns the value of the property for the first element in the results.

prop("propertyname","value")

sets the value of the property of all of the elements in the results.

prop(object)

sets the properties defined in the object in all of the elements in the results. 

prop("propertyname",function)

sets the property to the return value of the function in all of the elements of the result.

removeProp("propertyname")

attempts to remove the property from all of the elements in the result. 

Notice that removing native properties is not a good idea as it tends to generate errors. 

It is also worth knowing that there is a val method which returns the value property. This is covered in more detail in Chapter 10 on working with forms. 

Attributes v Properties – Checked

In most cases within a JavaScript program you want to know the current state of the UI and hence you generally want to use the property rather than the corresponding attribute. Also keep in mind that there are Element properties that do not correspond to attributes.

For example, the best known case is the use of checked to test if a checkbox has been checked. You can specify an initial or default state for this in the tag:

<input id="check1" type="checkbox" checked="checked" />

When the page first loaded this checkbox will display as checked. 

The user can then uncheck it if they want, but this doesn't change the checked attribute in the tag. As a result if you try:

$("#check1").prop("checked");

you will find it returns true or false depending on the current state, i.e. according to what the user has done. However:

$("#check1").attr("checked"); 

always returns "checked" because the value for the attribute in the tag doesn't change. Notice that the property is a Boolean and the attribute is a string. 

Note: that before jQuery 1.6 attr returned the same result as prop.   

CSS Attributes

The CSS attributes are slightly different in that they are coded as a string which is assigned to the style attribute. However, the style attribute is just a standard attribute and we already know how to deal with it.

For example, you can use the attr method to change the style attribute.

$("div").attr("style","width:300px");

However, the style attribute is so important, and a style string can be so long and complicated, that jQuery provides a method that allows you to work with "style" as if it was a collection of attributes in its own right. It is worth thinking of the CSS attributes as belonging to a single style object, which is an attribute of the DOM Element.

For example, the css method to set a style property without having to include the "style" attribute and without having to create a style string is:

$("div").css("width","300px");

Similarly, you can retrieve a single style setting without having to parse a style string:

var width=$("div").css("width");

Notice that this is the computed width retrieved from the first element in the results. 

What makes css so useful is that you can set multiple style values just as easily, for example:

$("div").css({"width":"300px","height":"400px"});

All you have to do is pass an object of name value pairs and the style will be set on all of the elements in the results. 

The css method also smooths over the differences between hyphenated and non-hyphenated versions of the same properties. For example you can use background-color or backgroundColor - and note that capitalization is important in all style properties. It also adds browser-specific prefixes if they are needed, which is reason enough to make use of it. 

If you want to do something really sophisticated you can pass css a function to set a property. As before, the function receives the element index and the current value of the property. For example:

$("div").css("width",function(i,val){return i*100;});

will set each div to width 0px, 100px, 200px and so on depending on its position in the results. 

There are other useful methods that can be used to modify the style of an element. For example:

addClass

and:

removeClass

adds or removes the specified class from each element in the results. You can also pass a function which can be used to compute a list of space-separated class names to add or remove.

There are also separate methods to get and set all of the css dimensions:

.height() .innerHeight() .outerHeight()
.width()  .innerWidth()  .outerWidth()

which get the current computed dimensions for the first element in the set of matched elements or set the attribute of every matched element.

The inner height/width includes padding but not the border. The outerheight/width includes padding, border, and optionally margin.

They return a number (without "px") specifying the value, or null if called on an empty set of elements.

There are two methods to get and set absolute and relative location attributes:

.offset()
.position()

These get the current coordinates of the first element, or set the coordinates of every element, in the set of matched elements, relative to the document (offset) or the parent (position). Both methods return a simple object with the properties top and left. For example:

$("img").offset().left;

gets the x co-ordinate of the first img tag and

$("img").offset({left:0,top:0})

sets the position of all of the images to 0,0. 

The positions may be fractional and they may be wrong if the user has a zoom applied in the browser. 

There are also two methods concerned with scroll bar positions: 

.scrollLeft()
.scrollTop()

These get the current horizontal position of the scroll bar for the first element in the set of matched elements, or set the position of the scroll bar for every matched element. The scroll bar position indicates the number of pixels of the element that have been scrolled off the screen.

 

smallcoverjQuery



Last Updated ( Saturday, 18 June 2022 )