Reputation: 131
The lines of code I wrote are based on the principle that because the presence of an object or array can be considered truthy, it's often used to check for the existence of an element within a page. But I'm guessing my condition fall into neither of this category. The code works when I put (el.className === "green") as a condition though.
var el = document.querySelector("ul");
if(el.hasAttribute('green')){
console.log("yes")
} else {
console.log("no")
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Practise App</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<ul class="green">
<li>Monday</li>
<li>Tuesday</li>
</ul>
<script src="index.js" type="text/javascript"></script>
</body>
</html>
Upvotes: 0
Views: 159
Reputation: 943207
hasAttribute
means "Has an attribute with this name"
You said class="green"
. It has a class
attribute, not a green
attribute (and can't have a green
attribute in valid HTML).
It does not mean "Has an attribute, of any name, with this value". DOM doesn't have a function that does that. You'd need to loop over each attribute (e.g. via the attributes
property) and test each one in turn.
Upvotes: 4