Reputation: 23
I'm trying use js onmousehover to hover over an image and in a seperate fixed location tell me the name of said image. I have successfully done this but I can only get it to work on the first element when I have about six that I need to do. here is a sample of my code:
function getElementsById(ids) {
var idList = ids.split(" ");
var results = [], item;
for (var i = 0; i < idList.length; i++) {
item = document.getElementById(idList[i]);
if (item) {
results.push(item);
}
}
return(results);
}
function hover(description) {
console.log(description);
document.getElementsById('content content1').innerHTML = description;
}
and to call it I've been using this:
<div class="product-description-box">
<p>
<div class="colorHeading">colors available: <span class="selectedColor" id="content"></span></div>
<div class="prodColors"></div>
</p>
</div>
I am using different ids for each section. Js is for sure not my strong suit so any help would be appreciated!
Upvotes: 2
Views: 288
Reputation: 724
A faster way of doing it is to pull your elements collection and then convert it into an array:
Like so:
[].slice.call(document.getElementsByClassName("box"))
.forEach(function(element) {element.addEventListener("mouseover", checkBoxColor);});
This calls slice on the collection of HTML elements returned by getElementsByClassName in order to convert it into an Array. After that I run the forEach method to add the event listener to each HTML element.
Fiddle: https://jsfiddle.net/0saLvq2q/
In your case if you need to return multiple elements by many different ID's you can use querySelectorAll() to pull the elements instead of getElementsByClassName().
Upvotes: 2
Reputation: 470
'ids' isn't automatically a list. What you want to use is the Arguments Object.
function getElementsById() {
var i, results = [], item;
for (i = 0; i < arguments.length; i++) {
item = document.getElementById(arguments[i]);
if (item) {
results.push(item);
}
}
return(results);
Upvotes: 0