I have to push in my array some Dom elements, and sometimes, to remove then from the array.
Here is what i'm doing:
var myDOMS = new Array();
myDOMS.push($("#myDiv"));
var element_to_remove = $("#myDiv");
var index = $.inArray(element_to_remove, myDOMS);
if (index > -1) {
myDOMS.splice(index, 1);
}
The part about removing doesn't work. Do you know what I'm doing wrong? Is it possible?
Every time you evaluate $("#myDiv")
you will get a new object back. So this is never true:
$("#myDiv") === $("#myDiv")
If you want to work like this, you should really use the DOM element references. Something like this:
var myDOMS = new Array();
myDOMS.push($("#myDiv").get(0));
var element_to_remove = $("#myDiv").get(0);
var index = $.inArray(element_to_remove, myDOMS);
console.log(index);
if (index > -1) {
myDOMS.splice(index, 1);
}
First of all, a correction.
$(XYZ)
gets you a new object that contains a collection of all DOM elements matched by the selector (the XYZ
part). with that, here is the solution without jQuery complications:
var elements = []; //prefer literal constructor over "new Array();" for brevity elements.push(document.getElementById("myDiv")); var element_to_remove = document.getElementById("myDiv"); var index = elements.indexOf(element_to_remove); console.log("element index: "+index); if(index !== -1){ //element was present in the array elements.splice(index,1); }
<div id="myDiv"></div>
So the issue that you are having is that when you use a jQuery selector, you create a unique jQuery object (or collection of objects, if there is more than one), that contains a bunch of information about the matching element, including a reference to the DOM element itself (the first bit of information, referenceable by $("#someElement")[0]
Since these objects are unique, while they may contain identical information about the returned element, the objects themselves are not equal. So, for:
var bodyRef1 = $("body");
var bodyRef2 = $("body");
var bodyRef3 = $("body");
You will find that the values contained in the object are all equal:
bodyRef1[0] === bodyRef2[0] === bodyRef3[0]
bodyRef1.context === bodyRef2.context === bodyRef3.context
etc. . . .
The objects themselves are not
bodyRef1 !== bodyRef2 !== bodyRef3
In your case, unless there is a specific reason why you need to have the elements selected in a jQuery format, you might actually be better off simply doing a native JavaScript selection, and remove the extra layer of complexity:
var myDOMS = new Array();
myDOMS.push(document.getElementById("myDiv"));
var element_to_remove = document.getElementById("myDiv");
var index = $.inArray(element_to_remove, myDOMS);
if (index > -1) {
myDOMS.splice(index, 1);
}
This works because the native JS selection returns only a reference to the DOM element.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.