Learn jquery from scratch (iv) attributes and styles for manipulating elements using jquery

Source: Internet
Author: User

This series of articles navigation

Learn jquery from scratch (iv) attributes and styles for manipulating elements using jquery

I. Summary

This article explains how to use jquery to get and manipulate the attributes and CSS styles of elements. The distinction between DOM attributes and element attributes is worth learning.

Two. Preface

Through the previous chapters we have been able to fully control the jquery package set, either by selecting the object through the selector or by removing it from the package set and filtering the element. This chapter explains how to use jquery to get and modify element properties and styles.

Three. Distinguishing Dom attributes from element attributes

An IMG tag:

<srcIDaltclass/>    

Usually developers are accustomed to ID, SRC, alt, etc. called "attributes" of this element. I call it "element attribute". But when parsing a DOM object, the actual browser eventually parses the tag element into a "DOM object" and stores the element's element attribute as a "Dom attribute." There is a difference between the two.
Although we set the src of the element to be relative to the path: images/image.1.jpg
However, in the DOM properties, it is converted to an absolute path: http://localhost/images/image.1.jpg.

Even some of the "element properties" and "Dom properties" have different names, such as the above element attribute class, which is converted to DOM property and corresponds to classname.

Keep in mind that in JavaScript we can get or set the DOM properties directly:

    <Type= "Text/javascript">        $ (var img1 = document.getElementById (</Script >      


So if you want to set the CSS style class for an element, use "Dom attribute" className instead of "element attribute" class:

"ClassB";

Four. Operation "Dom Properties"

There is no function to wrap the DOM properties in jquery because it is simple to get and set DOM properties using JavaScript. The each () function is provided in jquery to traverse the jquery wrapper set, where the this pointer is a DOM object, so we can apply this with native JavaScript to manipulate the DOM properties of the element:

            $ ("img"). each (function (index) {                alert ("changed"; Alert (this.alt);});   

The following is a description of each function:

Each (callback) Returns: jquery Package Set

Executes the callback method on each element in the wrapper set. Where the callback method takes a parameter that represents the index value of the current traversal, starting at 0.

Five. Operation "Element Properties"

We can use GetAttribute and setattribute in JavaScript to manipulate element attributes of elements.

In jquery, you are provided with a attr () wrapper set function that allows you to manipulate the attributes of all the elements in the wrapper set:

Name Description Example

attr (name)

Gets the property value of the first matching element. This method makes it easy to get the value of an attribute from the first matching element. Returns undefined if the element does not have a corresponding attribute. Returns the SRC attribute value of the first image in a document:
$ ("img"). attr ("src");
Attr (properties)

Sets an object in the form of a "name/value" as a property of all matching elements.

This is the best way to set many properties in bulk in all matching elements. Note that if you want to set the class property of an object, you must use ' className ' as the property name. Or you can use. addclass (Class) and. Removeclass (Class) directly.

Set the SRC and ALT attributes for all images:
$ ("img"). attr ({src: "test.jpg", alt: "Test Image"});
attr (key, value) Sets a property value for all matching elements. To set the SRC attribute for all images:
$ ("img"). attr ("src", "test.jpg");
attr (Key, FN)

Sets a computed property value for all matching elements.

Instead of providing a value, you provide a function that is evaluated by the function as the value of the property.

Set the value of the SRC attribute to the value of the title property:
$ ("img"). attr ("title", function () {return this.src});
REMOVEATTR (name) Remove an attribute from each matching element Delete the src attribute of the image in the document:
$ ("img"). Removeattr ("src");

When using the ID selector, you often return a jquery wrapper set with only one object, which is often used to get its element properties using the attr (name) function:

function TestAttr1 (event) {   alert ($ ("#hibiscus"). attr ("class"));}  


Note the attr (name) function returns only the specific element property value of the first matching element. attr (key, name) sets the attributes of the elements in all packages set:

Modifies the ALT attribute of all IMG elements $ ("img"). attr ("modified alt attribute");


attr (properties) can modify multiple element properties at once:

$ ("img"). attr ({title:"Modify ALT attribute at the same time"}); 


In addition, although we can use removeattr (name) to delete element attributes, the corresponding DOM attribute is not deleted, only the value of the DOM property is affected.

For example, removing the readonly element attribute of an INPUT element causes the corresponding DOM property to become false (that is, input becomes editable):

$ ("#inputTest"). Removeattr ("readonly"); 

Six, modify CSS style

Modify the style of the element, we can modify the element CSS class or directly modify the style of the element.

One element can apply more than one CSS class, but unfortunately in the DOM attribute it is stored in a space-delimited string, not an array. So if we want to add or delete multiple attributes to an element in the original JavaScript era, we have to manipulate the string ourselves.

jquery makes it all the more simple. We don't have to do those boring jobs anymore.

1. Modifying CSS Classes

The following table is a way to modify the CSS class-related jquery method:

Name Description Instance

AddClass (classes)

Adds the specified class name for each matching element. Add the ' selected ' class to the matched element:
$ ("P"). AddClass ("selected");
Hasclass (Class) Determines if at least one element in the wrapper set has applied the specified CSS class
$ ("P"). Hasclass ("selected");
Removeclass ([classes]) Removes all or the specified class from all matching elements. Remove the ' selected ' class from the matching element:
$ ("P"). Removeclass ("selected");
Toggleclass (Class) Delete (add) A class if it exists (does not exist). Toggle the ' selected ' class for the matching element:
$ ("P"). Toggleclass ("selected");
Toggleclass (class, switch) When switch is true, the class is added,
Delete class when switch is False

Toggle Highlight Style Every three clicks:
var count = 0;
$ ("P"). Click (function () {
$ (this). Toggleclass ("Highlight", count++% 3 = = 0);
});

Using the method above, we can modify the CSS class of the element like a collection, and no longer have to parse the string manually.

Note that the parameters of AddClass (Class) and removeclass ([classes]) can pass through multiple CSS classes at once, separated by spaces, such as:

$ ("#btnAdd"). Bind (function (event) {$ ("P"). AddClass ("colorred borderblue");});    


The parameters of the Removeclass method are optional, and if you do not pass in the parameters, all CSS classes are removed:

$ ("P"). Removeclass ()

2. Modifying CSS Styles

Also when we want to modify an element's specific CSS style, that is, to modify the element property "style", jquery also provides the appropriate method:

Name Description Instance
CSS (name) Accesses the style properties of the first matching element. Gets the value of the color style property of the first paragraph:

$ ("P"). CSS ("color");

CSS (properties)

Sets a "name/value pair" object to the style attribute of all matching elements.

This is the best way to set a large number of style attributes on all matching elements.

Sets the font color for all paragraphs to red and the background to blue:
$ ("P"). CSS ({color: "#ff0011", Background: "Blue"});

CSS (name, value)

In all matching elements, set the value of a style property.

Numbers are automatically converted to pixel values

Set all paragraph fonts to red:

$ ("P"). CSS ("Color", "red");

Seven. Get Common Properties

Although we can get almost all the information of an element by getting properties, attributes, and CSS styles, note the following experiment:

<!DOCTYPEHtmlPublic"-//w3c//dtd XHTML 1.0 transitional//en""Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><Htmlxmlns= "Http://www.w3.org/1999/xhtml"><Head><Title> Get Object width</Title><ScriptType= "Text/javascript"Src= "Scripts/jquery-1.3.2-vsdoc2.js"></Script> <script type="Text/javascript" > $ (function () {alert ("attr (\" width\ "):" + $ ("#testDiv"). attr ("width"));undifined Alert ("CSS (\" width\ "):" + $ ("#testDiv"). CSS ("width"));Auto (IE6) or 1264PX (FF) alert ( "width ():" + $ (//correct value 1264 alert ( "Style.width:" + $ ( "#testDiv") [0]. Style.width); //null}) </script></ head><body > <div id= " Testdiv "> Test text </div></body></ Html>             


We want to get the width of the test layer and use the attr method to get "element attribute" to undifined because it does not add width to the div. While using the CSS () method, although the value of the style property can be obtained, but the results returned in different browsers are different, IE6 returns auto, while the FF returns the correct value but with "px" behind it. So jquery provides the width () method, which returns the correct value without PX.

For the above question, jquery provides a way to get and set the common properties, such as width () the user gets the widths of the elements, and width (val) is used to set the element width.

The following methods can be used to get the common property values of an element:

1. Width and height related height and width
Name Description Example
Height () Gets the height value (px) that is currently computed for the first matching element. Get the height of the first paragraph:
$ ("P"). Height ();
Height (val) Sets the value of the CSS height (hidth) property for each matching element. If no units are explicitly specified (for example: EM or%), use PX. Set the height of all paragraphs to 20:

$ ("P"). Height (20);

Width () Gets the width value (px) currently computed for the first matching element. Get the width of the first paragraph:
$ ("P"). width ();
Width (val)

Sets the value of the CSS width property for each matching element.

If no units are explicitly specified (for example: EM or%), use PX.

Set the width of all paragraphs to 20:

$ ("P"). Width (20);

Innerheight ()

Gets the inner area height of the first matched element (including padding, excluding borders).
This method is valid for both visible and hidden elements.

See the last example
Innerwidth ()

Gets the inner area width of the first matched element (including padding, excluding borders).
This method is valid for both visible and hidden elements.

See the last example
Outerheight ([margin])

Gets the outer height of the first matching element (including padding and borders by default).
This method is valid for both visible and hidden elements.

See the last example
Outerwidth ([margin])

Gets the outer width of the first matching element, including padding and borders by default.
This method is valid for both visible and hidden elements.

See the last example

The difference between the three functions of "inner", "outer" and height/width in obtaining a long-width function:

Outerwith can accept a bool value parameter to indicate whether the margin value is calculated.

Believe this graph at a glance the range that each function takes. The picture shows the width as an example, and the functions of height are the same.

2. Location-related positioning

In addition, in some scripts that design sets of popup objects, it is often necessary to dynamically get the popup coordinates and set the position of the elements.

But there are a lot of ways to calculate locations with browser compatibility issues, and jquery provides us with location-related functions:

Name Description Example
Offset ()

Gets the relative offset of the matching element in the current window.

The returned object contains two shaping properties: Top and left. This method is valid only for visible elements.

Gets the offset of the second paragraph:
var p = $("p:last"); 
var offset = p.offset(); 
p.html( "left: " + offset.left + ", top: " + offset.top );
Position ()

Gets the offset of the matching element relative to the parent element.

The returned object contains two shaping properties: Top and left. To calculate the results accurately, use pixel units on the padding, border, and fill properties. This method is valid only for visible elements.

Gets the offset of the first paragraph:
var p = $("p:first"); 
var position = p.position(); 
$("p:last").html( "left: " + position.left + ", top: " + position.top );
ScrollTop ()

Gets the offset of the match element at the top of the scroll bar.

This method is valid for both visible and hidden elements.

Gets the offset from the top of the first paragraph relative to the scroll bar:
var p = $("p:first"); 
$("p:last").text( "scrollTop:" + p.scrollTop() );
ScrollTop (Val)

When you pass a parameter value, set the top offset of the vertical scroll bar to that value.

This method is valid for both visible and hidden elements.

To set the vertical scroll bar value:
$("div.demo").scrollTop(300);
ScrollLeft ()

Gets the offset to the left of the matching element relative to the scrollbar.

This method is valid for both visible and hidden elements.

Gets the offset to the left of the first paragraph relative to the scroll bar:
var p = $("p:first"); 
$("p:last").text( "scrollLeft:" + p.scrollLeft() );
ScrollLeft (Val)

When you pass a parameter value, set the left offset of the horizontal scrollbar to that value.

This method is valid for both visible and hidden elements.

Sets the offset to the left of the relative scroll bar:
$("div.demo").scrollLeft(300);

Eight. Summary

This article focuses on using jquery to manipulate the attributes of elements and modify styles. Please pay attention to the differences between element attributes and DOM attributes. The next article explains the most important events, how to bind events, manipulate event objects, and so on.

Learn jquery from scratch (iv) attributes and styles for manipulating elements using jquery

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.