Operate attributes and styles of Elements Using jQuery

Source: Internet
Author: User
Introduction: jquery tutorial 4: attributes and styles of jQuery operation elements. This article describes how to use jQuery to obtain and operate the attributes and CSS styles of elements. the distinction between DOM attributes and element attributes is worth learning. i. this article explains how to use jQ ...... jquery tutorial 4: attributes and styles of jQuery operation elements

Jquery tutorial 4: attributes and styles of jQuery operation elements. This article describes how to use jQuery to obtain and manipulate attributes and CSS styles of elements. the distinction between DOM attributes and element attributes is worth learning.

I. Summary

This article explains how to use jQuery to obtain and operate the attributes and CSS styles of elements. The distinction between DOM attributes and element attributes is worth learning.

  Ii. Preface

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.

3. differentiate DOM attributes and element attributes

An img Tag:

<"Html"> img src "kwrd"> = "images/image.1.jpg" "attr"> id = "hibiscus" "attr"> "attr"> "kwrd">/>

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 we have set the relative path of the element src: images/image.1.jpg
However, in the "DOM attribute", it is converted to an absolute path: http: // localhost/images/image.1.jpg.

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 ":

<"Html"> script type "kwrd"> = "text/javascript" "kwrd" >$ ("kwrd"> function (){
"Kwrd"> var img1 = document. getElementById ("str"> "hibiscus ");
Alert (img1.alt );
Img1.alt = "str"> "Change the alt element attribute ";
Alert (img1.alt );
})
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 ";
4. 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:

$ ("Img"). each ("kwrd"> function (index ){
Alert ("str"> "index:" + index + "str"> ", id:" + "kwrd"> this. id + "str"> ", alt:" + this. alt );
This. alt = "str"> "changed ";
Alert ("str"> "index:" + index + "str"> ", id:" + "kwrd"> this. id + "str"> ", alt:" + this. alt );
});

The following describes the each function:

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.

  5. 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:

Function testAttr1 ("kwrd"> event ){
Alert ($ ("# hibiscus"). attr ("str"> "class "));
}


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 attributes of all img elements $ ("str"> "img"). attr ("str"> "alt", "modified alt attributes ");


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


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


In addition, although we can use RemoveAttr (name)The element attribute is deleted, but the corresponding DOM attribute is not deleted, and only the DOM attribute value is affected.


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 ):

$ ("# InputTest"). removeAttr ("str"> "readonly ");
6. 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 (ADD) a class if it exists (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:AddClass (class) AndRemoveClass ([classes])Parameters can be input into multiple css classes at a time, separated by spaces, such:

$ ("# BtnAdd "). bind ("str"> "click", "kwrd"> function ("kwrd"> event) {$ ("str"> "p "). addClass ("str"> "colorRed borderBlue ");});


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


$ ("P"). removeClass ()
2. Modify the CSS style

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 ");

7. obtain common attributes

Although we can obtain almost all information about elements by obtaining attributes, features, and CSS styles, pay attention to the following experiment:

DOCTYPE html "attr"> PUBLIC "kwrd"> "-// W3C // dtd xhtml 1.0 Transitional // EN" "kwrd"> "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Get object width Script
$ (Function ()
{
Alert ("str"> "attr (\" width \ "):" + $ ("str"> "# testDiv "). attr ("str"> "width"); "rem"> // undifined alert ("str"> "css (\" width \"): "+ $ (" str ">" # testDiv ").css (" str ">" width ");" rem "> // auto (ie6) or 1264px (ff) alert ("width ():" + $ ("# testDiv "). width (); // the correct value is 1264 alert ("style. width: "+ $ (" # testDiv ") [0]. style. width); // null value })
Script> "kwrd">> <"Html"> body> "kwrd"> id = "testDiv" "kwrd"> test text "kwrd">> Body> "kwrd">>


We want to obtain the width of the test layer and use the attr method to obtain the "element feature" as undifined, because no width is added for the div. the css () method can be used to obtain the value of the style attribute, but different results are returned in different browsers. in IE6, auto is returned, while the correct value is returned in FF, it is followed by "px ". therefore, jQuery provides the width () method, which returns a correct value without px.


To solve the preceding problem, jQuery provides methods for obtaining and setting common attributes. For example, width () is used to obtain the width of an element, while width (val) is used to set the width of an element.

The following methods can be used to obtain common attribute values of an element:

1. Width and Height related Height and Width
Name Description Example
Height () Obtains the current calculated height (px) of the First Matching Element ). Obtain the height of the first section:
$ ("P"). height ();
Height (val) Set the CSS height (hidth) attribute value for each matching element. If the unit (such as em or %) is not explicitly specified, px is used. Set the height of all paragraphs to 20:

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

Width () Obtains the current calculated width (px) of the First Matching Element ). Obtain the width of the first segment:
$ ("P"). width ();
Width (val)

Set the CSS width attribute value for each matching element.

If the unit (such as em or %) is not explicitly specified, px is used.

Set the width of all paragraphs to 20:

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

InnerHeight ()

Obtain the height of the interior area of the First Matching Element (including the padding and not the border ).
This method is effective for both visible and hidden elements.

See the final example
InnerWidth ()

Obtain the width of the area inside the First Matching Element (including the padding and not the border ).
This method is effective for both visible and hidden elements.

See the final example
OuterHeight ([margin])

Obtain the external height of the First Matching Element (including the padding and border by default ).
This method is effective for both visible and hidden elements.

See the final example
OuterWidth ([margin])

Obtain the external width of the First Matching Element (including the padding and border by default ).
This method is effective for both visible and hidden elements.

See the final example

The differences between the "inner", "outer", and "height/width" functions are described as follows:

OuterWith can accept a bool value parameter to indicate whether to calculate the margin value.

I believe the range obtained by each function in this example. The image uses width as an example to describe the function of height.

2. Positioning

In addition, in some design set pop-up object scripts, it is often necessary to dynamically obtain the pop-up coordinates and set the element position.

However, there are browser compatibility issues in many Location Calculation Methods. jQuery provides location-related functions for us:

Name Description Example
Offset ()

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

The returned object contains two integer attributes: top and left. This method is only valid for visible elements.

Get the offset of the second segment:
Var p = $ ("p: last ");
Var offset = p. offset ();
P.html ("left:" + offset. left + ", top:" + offset. top );
Position ()

Obtains the offset of a matched element from its parent element.

The returned object contains two integer attributes: top and left. For precise calculation results, use the pixel unit in the padding, border, and fill attributes. This method is only valid for visible elements.

Get the first offset:
Var p = $ ("p: first ");
Var position = p. position ();
$ ("P: last" ).html ("left:" + position. left + ", top:" + position. top );
ScrollTop ()

Obtains the offset of the matching element relative to the top of the scroll bar.

This method is effective for both visible and hidden elements.

Get the offset of the first segment relative to the top of the scroll bar:
Var p = $ ("p: first ");
$ ("P: last"). text ("scrollTop:" + p. scrollTop ());
ScrollTop (val)

When passing the parameter value, set the vertical scroll bar top offset to this value.

This method is effective for both visible and hidden elements.

Set the vertical scroll bar value:
$ ("Div. demo"). scrollTop (300 );

ScrollLeft ()

Returns the offset of the matching element to the left of the scroll bar.

This method is effective for both visible and hidden elements.

Get the offset of the first segment relative to the left of the scroll bar:
Var p = $ ("p: first ");
$ ("P: last"). text ("scrollLeft:" + p. scrollLeft ());
ScrollLeft (val)

When passing the parameter value, set the left offset of the horizontal scroll bar to this value.

This method is effective for both visible and hidden elements.

Set the offset relative to the left of the scroll bar:
$ (& Quot; div. demo & quot;). scrollLeft (300 );

8. Summary

This article describes how to use jQuery to operate on the attributes of elements and modify styles. please pay attention to the differences between element attributes and DOM attributes. the next article will explain the most important events and how to bind events and operate event objects.

If you think "jquery tutorial entry 4: attributes and styles of jQuery operation elements" is good, you can use the sharing tool to share it with your friends!

Related Article

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.