Question

My app uses a Parse backend to keep a running list of all the concerts in my area that my friends and I are interested in.

On the main page I use a parse query display a module for each show stored in the database. As each module is created, I use this code to add a data attribute to the show's outermost div, corresponding to the show's object ID in parse:

var showId = object.id;
$("div.show_module:last").data("showId", showId);

I'm successfully able to retrieve the showId of a specific show when the user clicks on the show's module:

$("#showsList").delegate(".showModuleBody", "click", function() {
    var storeObjectId = $(this).closest("div.show_module").data("showId");
});

That all works great, proving that assigning the data-attribute is working.

Where I'm running into trouble is trying to find an element with a specific data attribute or a specific value for that attribute on a given page. The end goal is to get the y-offset of that div so I can scroll the page to the appropriate spot. I assumed I could use the following code to find the element, but it isn't working -

// find all elements with class .show_module
var allShows = document.querySelectorAll('.show_module');

// find all elements with showId data attribute
var showsWithShowId = document.querySelectorAll('[data-showId]');

// find all elements with a specific showId data attribute
var showToFind = document.querySelectorAll("[data-showId='2']");

The first of those 3 works, proving that all the elements I'm interested in are loaded into the page by the time I'm calling this function, but the 2nd and 3rd queries return nothing.

Any idea what I'm doing wrong here? Is it something with syntax? Is querySelectorAll just incompatible with how I'm setting the data attribute?

I tried to include only what I figured are the salient bits of code, but if more is necessary please let me know.

Was it helpful?

Solution 2

jQuery's .data method does not create a HTML attribute, but associates a value in its internal data store with the element.

If you want to set a data attribute with jQuery, then you need to use:

$("div.show_module:last").attr("data-showId", showId);

To get the value, you can use .data('showId') or .attr('data-showId').

(note that HTML attributes are case-insensitive, so you can also write "data-showid" instead.)

OTHER TIPS

Try This

$('*[data-customerID="22"]');

For more info, look here:

Selecting element by data attribute

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top