Reputation: 1291
const box = document.querySelectorAll(".box");
console.log(box.length);
const direction = [
"top-start",
"bottom-start",
"left-start",
"right-start",
"top-center",
"bottom-center",
"left-center",
"right-center",
"top-end",
"bottom-end",
"left-end",
"right-end"
];
box.forEach((el, index) => {
for (let i = 0; i < direction.length; i++) {
CreateTooltip(el, direction[index], "Hello, World!");
}
});
The above mentioned code rendering 144
tooltips in DOM
and I want only 12 with each should have different directions. I don't why this loop is not working! I tried to add forEach
loop inside for
loop but still the problem is same.
NOTE As some of you asked I pasted my entire code. Hope it will help you and then you will help me. 😅
Upvotes: -1
Views: 74
Reputation: 11
Your code is working well, as you are iterating over list of boxes and inside that you have another iteration, so the result of your code will always be (number of boxes)*(number of directions) = 144..
So you can Iterate only on boxes or on direction by manipulating one and other lists by there index numbers as given below..
$(box).each(function(i,v){console.log(direction[i])})
Upvotes: 1
Reputation: 10898
From what you have stated, namely wanting 12 tooltips (same as direction
index counts) but getting 144 tooltips (144/12 = 12) you should have 12 elements with .box
class in your page. the problem is in your query selection.
const box = document.querySelectorAll('.box');
console.log(box.length); // this should show 12
what you need to do is to set an ID for your element or create a loop for the box (array at this point) and execute your CreateTooltip
logic for each of them separately.
Note: I suggest you to test your CreateTooltip
in a testing environment (separated file created to test your code) with only one .box
element, it's possible that the library you're using does not support multiple calls of CreateTooltip
for a single element, that might be the reason you're getting 144 elements instead of 12.
Upvotes: 0
Reputation: 177
You can pass in the index of each element like this and get the corresponding value from the direction array
box.forEach((element, index) => {
CreateTooltip(element, direction[index], 'Hello, World!');
})
Upvotes: 2
Reputation: 1145
If you are using Queryselectorall , if it is class use dot , or if you are using id use #
const box = document.querySelectorAll('.box');
Upvotes: 0