Reputation: 15
I would like the current selector to be compared against a stored node in a JavaScript if condition.
In my code I have created an array of image nodes and li nodes. I would like to be able to compare the li that is being currently hovered over by the user to the elements in the links array, e.g., is the currently hovered link the same as links[0]?
I have tried many ways to check equality between jQuery(this) and the links, but I cannot get an if statement to find them equal. Can you tell me how to compare the current selector to selector locations stored in an array?
Below is my code (I am using jQuery for my selector because this is a Wordpress website):
jQuery("li.menu-cloud").hover( function(){
// Identify the containers of the links and the featured images:
var nav = document.getElementById("nav");
var holder = document.getElementById("img-holder");
// Creates an array of the individual links and featured images of the menu links:
var pics = holder.getElementsByTagName("img");
var links = nav.getElementsByTagName("li");
//Store current li in a variable to test:
var element = jQuery(this);
if ( links[0] == element )
{
alert("links[0] equals this element");
}
else {}
},
function() {
alert("You have left a menucloud link.");
});
Upvotes: 0
Views: 87
Reputation: 1353
You can add attribute for your li.menu-cloud
and nav.li
as data-name="img1"
, and so you can compare between those attributes like this code:
$("li.menu-cloud").each(function () {
$(this).on('hover',function () {
// Identify the containers of the links and the featured images:
var nav =$("#nav");
var holder = $("#img-holder");
var data_name_img=$(this).attr('data-name');
// Creates an array of the individual links and featured images of the menu links:
var pics = holder.find("img");
var links = nav.find("li");
//Store current li in a variable to test:
var element = jQuery(this);
$.each(links,function (i,v) {
if (data_name_img===$(v).attr('data-name')){
console.log($(v)+" equals this element");
}
})
})
})
Upvotes: 0
Reputation: 5967
You're comparing the array item (DOM element) to a jQuery object. You should instead compare the actual element selected by jQuery, which you can do using an index accessor (element[0]
) or the .get()
method (element.get(0)
)
e.g.
if (links[0] == element[0])
or
if (links[0] == element.get(0))
Upvotes: 1