Jquery objects and javascript objects or DOM objects convert to each other

  • 2020-03-30 03:38:49
  • OfStack

JQuery objects are objects that are generated after a DOM object is wrapped through jQuery. JQuery objects are unique to jQuery. They can use jQuery methods, but not DOM methods. For example: $(" # img "). The attr (" SRC ", "test. JPG"); The $("#img") here is the jQuery object.

DOM objects are just some of the object manipulation inherent in Javascript. DOM objects can use methods inherent in Javascript, but not jQuery methods. For example: document.getelementbyid ("img").src = "test.jpg"; Here document.getelementbyid ("img") is the DOM object.

# $(" img "). Attr (" SRC ", "test. JPG"); And the document. The getElementById (" img "). The SRC = "test. JPG"; $("#img").src = "test.jpg"; Or the document. The getElementById (" img "). The attr (" SRC ", "test. JPG"); All wrong.

Another example is this, which is often written in jQuery: this.attr(" SRC ","test.jpg"); This is a DOM object and.attr(" SRC ","test.jpg") is a jQuery method. To solve this problem, turn a DOM object into a jQuery object, such as $(this).attr(" SRC ","test.jpg");

1. DOM object is converted into jQuery object

For a DOM object that is already a DOM object, you only need to wrap the DOM object with $() to get a jQuery object

Such as:


var v = document.getElementById("v"); //DOM object
var $v = $(v); //jQuery  object 

Once transformed, you can use any jQuery method you want.

2. Transform jQuery objects into DOM objects

There are two ways to convert a jQuery object into a DOM object: [index] and. Get (index);

(1) jQuery object is a data object, you can get the corresponding DOM object through the method of [index].

Such as:


var $v = $("#v"); //The jQuery object
var v = $v[0]; //DOM object
alert(v.checked); // To detect the checkbox Whether or not selected 

(2) jQuery itself provides. Get (index) method to get the corresponding DOM object

Such as:


var $v = $("#v"); //The jQuery object
var v = $v.get(0); //DOM object ($v.geet ()[0] also works)
alert(v.checked); // To detect the  checkbox  Whether or not selected 

Through the above methods, jQuery objects and DOM objects can be arbitrarily converted to each other. It needs to be emphasized that DOM objects can only use methods in DOM, while jQuery objects cannot use methods in DOM.


Related articles: