Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why do I get undefined when trying to get a dynamically added data attribute?

I’m trying to get the value for data-tab-id based on the class .tab-btn.active | however, the result keeps returning undefined.

This is where I add the data attribute

$navigation.find(".tab-btn").each(function(i, ele) {
        $(ele).attr("data-tab-id", i);
    });

This is where I retrieve it

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var autoSwitch = setInterval(function() {

    //Get maximum # of tabs
    maxTabs = $(".tab-btn").length;
                        
    //Get the currently active button
    pastActiveBtn = $(".tab-btn").find(".active");
    pastId = pastActiveBtn.data('tabId'); //I have also tried tab-id; also 'undefined'

    console.log(pastId); //OUTPUT = undefined

});

If anyone knows why I am getting this, I’d appreciate it.

>Solution :

Try using
pastActiveBtn = $(".tab-btn").filter(".active");
Filter will look at the currently matched element, while find will look at the descendants.
More details about the difference between filter and find in this answer.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading