jQuery getting id via $(this) not working

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">
    <meta charset="utf-8">
    <link rel="stylesheet" href="./style.scss">
    <!-- 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">
    <div id="background">
          <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 id="search_bar">
            <input id="bar" type="text" placeholder="paste a url to add it here">
            <button id="addItem">+</button>

        <section id="favs">
          <div id="link_view"></div>
          <div id="icon_view"></div>
          <div id="folder_view"></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>


And this is the jQuery code:

    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.

You’re using an arrow function, which has no this context.

function () {


(e) => {
1 Like

Thanks, I had no idea that arrow functions were functionally different to regular functions.