I am encountering an issue when trying to get the id attribute of an element using the $(this) keyword and the attr(“id”) method.
Here is my HTML code so far:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="./style.scss">
<title>favs</title>
<!-- Prevents user scaling -->
<meta name="viewport" content="width=device-width, user-scalable=no"/>
<!-- Mobile accessibility tag -->
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
<div id="background">
<main>
<header>
<div id="view_settings">
<button id="links" class="view">links</button>
<button id="all" class="view">all</button>
<button id="folders" class="view">folders</button>
</div>
<div id="search_bar">
<input id="bar" type="text" placeholder="paste a url to add it here">
<button id="addItem">+</button>
</div>
</header>
<section id="favs">
<div id="link_view"></div>
<div id="icon_view"></div>
<div id="folder_view"></div>
</section>
</main>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script type="text/javascript" src="./main.js"></script>
</body>
</html>
And this is the jQuery code:
$(".view").click(()=>{
console.log($(".view").attr("id")); // Logs "#links"
console.log($(".view", this).attr("id")); // Logs undefined
console.log($(this).attr("id")); // Logs undefined
});
I have the jQuery CDN above the link to my main.js file at the bottom of the body element, so I don’t think that’s the issue here.