Home >Web Front-end >Front-end Q&A >What is the conversion method between jquery object and dom object

What is the conversion method between jquery object and dom object

WBOY
WBOYOriginal
2022-06-02 15:40:507357browse

Methods: 1. "obj[index]" and "obj.get(index)" methods. These two methods can convert jquery objects into dom objects. Index is the index of the DOM object in the jQuery object; 2. "$(DOM object)" method, which can convert the dom object into a jquery object.

What is the conversion method between jquery object and dom object

The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.

Conversion method between jquery object and dom object

1. Convert jQuery object into DOM object

jQuery object belongs to class Array object, which internally uses DOM objects as array elements. There are two ways to convert jQuery objects into DOM objects, namely "obj[index]" and "obj.get(index)". where index represents the index of the DOM object in the jQuery object. These two conversion methods are explained below.

(1)obj[index]

Convert jQuery object into DOM object through obj[index] method. The sample code is as follows.

<div>第1个div</div>
<div>第2个div</div>
<script>
//获取jQuery对象
var divs = $(&#39;div&#39;);
//通过索引的方式,将jQuery对象转换成DOM对象
var div1 = divs[0];
var div2 = divs[1];
//输出div元素的内容
alert(div1.innerHTML);    //输出结果:第1个div
alert(div2. innerHTML);    //输出结果:第2个div
</script>

As can be seen from the above code, a jQuery object can contain multiple DOM elements, and a specific DOM object can be retrieved through indexing.

(2) obj.get(index)

Convert jQuery object into DOM object through obj.get(index) method. The sample code is as follows.

<div>第1个div元素</div>
<script>
var result = $(&#39;div&#39;).get(0).innerHTML;
alert(result);    //输出结果:第1个div元素
</script>

2. Convert the DOM object into a jQuery object

var name = $(DOM对象)

Use the DOM object as a parameter of the $() function to convert it into jQuery Object, the sample code is as follows.

<button id="btn">say hello</button>
<script>
//获取DOM对象btn
var btn = document.getElementById(&#39;btn&#39;);
//将DOM对象转换成jQuery对象
var btnl = $(btn);
//验证转换结果
alert(btn === btnl[0]);    //输出结果: true
</script>

As can be seen from the above code, DOM objects and jQuery objects can be flexibly converted to each other during development.

Video tutorial recommendation: jQuery video tutorial

The above is the detailed content of What is the conversion method between jquery object and dom object. For more information, please follow other related articles on the PHP Chinese website!

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