Home » Jquery » javascript – jQuery $(this).data() returns undefined-Exceptionshub

javascript – jQuery $(this).data() returns undefined-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I’m trying to fix the following code:

const $configuratorMenus = $('.configurators-menu ul li');

$configuratorMenus.click(() => {

    let panelID = $(this).data("id");
    let panelID2 = $(this).attr("data-id");

    console.log(panelID, panelID2);

    //$(`#${panelID}`).slideToggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="configurators-menu">
    <ul>
        <li data-id="shapes">
            <a href="#">
                Shape
            </a>
        </li>
    </ul>
</div>

It keeps consoling undefined, what am I doing wrong? I couldn’t relate any other solution.

Note: I would like to solve this by using the arrow function.

How to&Answer:

Since you are using arrow function , this will refer window object in this case. You can use e.target.Where e is event object. Also the data attribute is on li but the event is originating from a. So change $configuratorMenus to $('.configurators-menu ul li a')

const $configuratorMenus = $('.configurators-menu ul li a');

$configuratorMenus.click((e) => {
  // get the parent element from the target
  let panelID = $(e.target).parent().data('id');
  console.log(panelID);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="configurators-menu">
    <ul>
        <li data-id="shapes">
            <a href="#">
                Shape
            </a>
        </li>
    </ul>
</div>

Answer:

This one should resolve your problem –

const configuratorMenus = $('.configurators-menu ul li a');

configuratorMenus.click(function () {
    let panelID = $(this).parent().data("id");
    console.log(panelID);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="configurators-menu">
    <ul>
        <li data-id="shapes">
            <a href="#">
                Shape
            </a>
        </li>
    </ul>
</div>