Home > Web Front-end > JS Tutorial > Introduction to methods of converting between jQuery objects and DOM objects_jquery

Introduction to methods of converting between jQuery objects and DOM objects_jquery

WBOY
Release: 2016-05-16 16:12:23
Original
1389 people have browsed it

Before discussing the exchange of jQuery objects and DOM objects, first agree on the style of defining variables. If the obtained object is a jQuery object, add $ before the variable, for example:

Copy code The code is as follows:

var $variable = jQuery object;

If the DOM object is obtained, it is defined as follows:
Copy code The code is as follows:

var variable = DOM object;

1. Convert jQuery object to DOM object

jQuery objects cannot use methods in DOM, but if you are not familiar with the methods provided by jQuery objects, or jQuery does not encapsulate the desired methods, and you have to use DOM objects, there are two methods below. jQuery provides two methods to convert a jQuery object into a DOm object, namely [index] and get(index).

(1) The jQuery object is an array object, and the corresponding DOM object can be obtained through the [index] method.

The jQuery code is as follows:

Copy code The code is as follows:

var $cr = $("#cr"); //jQuery object
var cr = $cr[0] //DOM object
alert(cr.checked) //Check whether this checkbox is checked

(2) Another method is provided by jQuery itself, and the corresponding DOM object is obtained through the get(index) method.

The jQuery code is as follows:

Copy code The code is as follows:

[js]var $cr = $("#cr");
var cr = $cr.get(0);
alert(cr.checked)

2. Convert DOM object into jQuery object

For a DOM object, you only need to wrap the DOM object with $() to get a jQuery object. The method is $(DOM object).

The jQuery code is as follows:

Copy code The code is as follows:

var cr = document.getElementByID("cr"); //DOM object
var $cr = $(cr);

After conversion, you can use any method in jQuery.

Through the above methods, jQuery objects and DOM objects can be converted to each other arbitrarily.

Finally, it is emphasized that only DOM objects can use methods in DOM. jQuery objects cannot use methods in DOM, but jQuery objects provide a more complete set of tools for operating DOM

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template