I have been working on tooltips and for that I created a javascript function Tooltip() in which I selected all the DOM elements like const targets = document.querySelectorAll('*') and after selecting all the elements, I addedforEach function on targets variable and inside for each function I created an if statement in which I checked if an element contains the specific attribute I mentioned in requiredAttrs array but it is not working somehow! And I don't know where I'm doing wrong.
COMPLETE CODE
function Tooltip() {
const requiredAttrs = ['data-tooltip', 'data-tooltip-position', 'data-tooltip-content'];
const targets = document.querySelectorAll('*');
targets.forEach((target, index) => {
if (target.hasAttribute(requiredAttrs[index])) {
console.log('Y');
} else {
console.log('No');
}
});
}
Tooltip();
<!DOCTYPE html>
<html dir="ltr" lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="public/css/main.css" />
<title>Pearl Framework</title>
</head>
<body class="vh-full grid-center">
<style>
body {
background-color: #a1a1a1;
}
.box {
width: 100px;
height: 100px;
background-color: purple;
}
</style>
<div
class="box"
data-tooltip="true"
data-tooltip-position="top-center"
data-tooltip-content="Hello, World!"
></div>
<script src="public/script/tooltip.js"></script>
</body>
</html>
As you can see a <div class="box"></div> has all 3 attributes so if statement should run but instead else part is running.