Home  >  Article  >  Web Front-end  >  How jQuery converts selected objects into original DOM objects_jquery

How jQuery converts selected objects into original DOM objects_jquery

WBOY
WBOYOriginal
2016-05-16 16:45:091264browse

In jQuery, the collection returned by selecting elements on a page is a jQuery object rather than the original DOM object. So only jQuery methods can be run. If you want to run DOM methods and properties on the selection set, the collection must be converted to a DOM object

For example, you cannot use it like this:

$('div').innerHTML = "hello world";

Because innerHTML is a property of the DOM and not a property of the jQuery object .If you really want to do this, then you need to convert the jQuery object into a DOM object. There are two methods.

①jQuery provides a core method get(), so the above can be written as $('div') .get().innerHTML = "hello world";

Of course, this corresponds to the situation where there is only one div in the page. If there are multiple divs.

Then this method is not easy to use. , you need to modify the code to select by passing the index value to get(index).

$("div").get(0).innerHTML = "hello world";

Of course, you can use jQuery’s built-in $.each loop to perform all assignment operations.

$div1 = $("div").get();

Copy code The code is as follows:

$.each($div1 , function(index, val) {
val.innerHTML = 'lc ' index;
});


②We can use [ ] to use arrays Get the content in the form.

For example, $('div')[0].innerHTML = "hello world";

Let's take a look at a complete example.
Copy code The code is as follows:





Books



  1. Head First jQuery

  2. Data Structrue and Algorithm with Javascript

  3. Nodejs up and running

  4. Node js with PHP expert

  5. Sharp jQuery

  6. Professional Javascript








Now I will add the process of converting DOM objects into jQuery objects.

Here I am using this example.
Copy the code The code is as follows:





Click Me





Here is the process of converting our DOM object into a jQuery object.

Note: In fact, it refers to our link object a. It is an ordinary DOM object, and we use it in the onclick event Pass this in.

Then we use $() to encapsulate the DOM object, and then we can use the addClass function.
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