Teach you how to use jQuery to operate on attributes and styles of elements (1)

Source: Internet
Author: User

Series of articles:

Learning jQuery from scratch to manage jQuery packaging Sets

Learning jQuery's omnipotent selector from scratch

Learning jQuery from scratch the JavaScript you must know

We have been able to fully control the jQuery packaging set through the previous chapters, whether by selecting an object through the selector, or deleting from the packaging set, filter elements. this chapter describes how to use jQuery to obtain and modify element attributes and styles.

1. differentiate DOM attributes and element attributes

An img Tag:

 
 
  1.    

Generally, developers are used to calling id, src, alt, and other "attributes" of this element ". I call it "element attribute ". however, when parsed to a DOM object, the actual browser will finally parse the tag element into a "DOM object" and store the "element attribute" of the element as "DOM attribute ". the two are different. although the element src is set to relative path: images/image.1.jpg, it is converted to absolute path: http: // localhost/images/image.1.jpg in "DOM attribute.

Even some "element attributes" and "DOM attributes" have different names. For example, the above element attribute class corresponds to the className after being converted to the DOM attribute.

Remember, in javascript, we can directly get or set the "DOM attribute ":

 
 
  1. <script type="text/javascript">    
  2.         $(function() {    
  3.             var img1 = document.getElementById("hibiscus");    
  4.             alert(img1.alt);    
  5.             img1.alt = "Change the alt element attribute";    
  6.             alert(img1.alt);    
  7.         })    
  8. </script>   

Therefore, to set the CSS style class of an element, you must use "DOM attribute" className "instead of" element attribute "class:

Img1.className = "classB ";

2. Operate "DOM attributes"

There is no function in jQuery to wrap "DOM attribute", because it is easy to use javascript to get and set "DOM attribute. the each () function provided by jQuery is used to traverse the jQuery package set. The this pointer is a DOM object, so we can apply this and use native javascript to manipulate the DOM attributes of the element:

The following describes the each function:

 
 
  1. $("img").each(function(index) {    
  2.                alert("index:" + index + ", id:" + this.id + ", alt:" + this.alt);    
  3.                this.alt = "changed";    
  4.                alert("index:" + index + ", id:" + this.id + ", alt:" + this.alt);    
  5.            });   

Each (callback) Returns: jQuery package set

Run the callback Method on each element in the wrapper set. The callback method accepts a parameter to indicate the index value of the current traversal, starting from 0.

3. Operate "element attributes"

We can use getAttribute and setAttribute in javascript to operate the "element attribute" of an element ".

In jQuery, you are provided with the attr () set function, which can simultaneously manipulate the attributes of all elements in the Set:

Name Description Example
Attr (name) Obtains the attribute value of the First Matching Element. This method can be used to conveniently obtain the value of an attribute from the First Matching Element. If the element does not have a property, undefined is returned. Return the src attribute value of the first image in the document:
$ ("Img"). attr ("src ");
Attr (properties) Set an object in the form of "name/value" to the attributes of all matching elements.

This is the best way to set multiple attributes in batches among all matching elements. Note: To set the class attribute of an object, you must use 'classname' as the attribute name. Or you can directly use. addClass (class) and. removeClass (class ).

Set the src and alt attributes for all images:
$ ("Img"). attr ({src: "test.jpg", alt: "Test Image "});
Attr (key, value) Set an attribute value for all matching elements Set the src attribute for all images:
$ ("Img"). attr ("src", "test.jpg ");
Attr (key, fn) Set a calculated attribute value for all matching elements.

Instead of providing a value, a function is provided. The value calculated by this function is used as the attribute value.

Set the src attribute value to the title attribute value:
$ ("Img"). attr ("title", function () {return this. src });
RemoveAttr (name) Deletes an attribute from each matching element. Delete the src attribute of the image in the document:
$ ("Img"). removeAttr ("src ");

When the id selector is used, the jQuery package set with only one object is often returned. In this case, the attr (name) function is often used to obtain its element attributes:

 
 
  1. function testAttr1(event) {    
  2.    alert($("#hibiscus").attr("class"));    
  3. }   

Note that the attr (name) function returns only the attribute values of the First Matching element. The attr (key, name) function sets the attributes of all elements in the packaging set:

// Modify the alt attribute of all img Elements

$ ("Img"). attr ("alt", "modified alt attributes ");

While attr (properties) can modify multiple element attributes at a time:

 
 
  1. $ ("Img"). attr ({title: "modified title", alt: "modifying alt attributes at the same time "});

In addition, although we can use removeAttr (name) to delete element attributes, the corresponding DOM attributes will not be deleted and will only affect the values of DOM attributes.

For example, if you remove the readonly attribute of an input element, the corresponding DOM attribute is changed to false (that is, the input is changed to editable State ):

 
 
  1. $("#inputTest").removeAttr("readonly");   

4. Modify the CSS style

Modify the element style. You can modify the element CSS class or directly modify the element style.

One element can apply multiple css classes, but unfortunately stored in the DOM attribute using a string separated by spaces, rather than an array. therefore, if you want to add or delete multiple attributes to an element in the original javascript era, you must operate the string yourself.

JQuery makes all this very simple. We no longer need to do boring work.

1. Modify the CSS class

The following table shows the jQuery Method for modifying the CSS class:

Name Description Instance
AddClass (classes) Add the specified class name for each matching element. Add the 'selected' class to the matched element:
$ ("P"). addClass ("selected ");
HasClass (class) Determine whether at least one element in the packaging set applies the specified CSS class. $ ("P"). hasClass ("selected ");
RemoveClass ([classes]) Deletes all or specified classes from all matching elements. Delete the 'selected' class from the matched element:
$ ("P"). removeClass ("selected ");
ToggleClass (class) Delete the added class if it does not exist. Switch the 'selected' class to the matching element:
$ ("P"). toggleClass ("selected ");
ToggleClass (class, switch) Add a class when switch is true,
Delete a class when switch is false.
Click to switch the highlighted style three times:
Var count = 0;
$ ("P"). click (function (){
$ (This). toggleClass ("highlight", count ++ % 3 = 0 );
});

Using the above method, we can modify the element's CSS class like a set, and no longer need to manually parse the string.

Note that parameters of addClass (class) and removeClass ([classes]) can be input into multiple css classes at a time and separated by spaces. For example:

 
 
  1. $("#btnAdd").bind("click", function(event) { $("p").addClass("colorRed borderBlue"); });   

The parameters of the removeClass method are optional. If no parameters are input, all CSS classes are removed:

 
 
  1. $("p").removeClass()   

2. Modify the CSS sample

Similarly, when we want to modify a specific CSS style of an element, that is, to modify the element attribute "style", jQuery also provides the corresponding method:

Name Description Instance
Css (name) Access the style attribute of the First Matching Element. Obtain the value of the color Style attribute of the first section:
$ ("P" ).css ("color ");
Css (properties) Set 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.

Set the font color of all paragraphs to red and the background to Blue:
$ ("P" ).css ({color: "# ff0011", background: "blue "});
Css (name, value) Set the value of a style attribute among all matching elements.

The number is automatically converted to the pixel value.

Set the font of all paragraphs to Red:
$ ("P" ).css ("color", "red ");


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.