简体   繁体   中英

querySelectorAll to find matching data-attribute

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.

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.)

Try This

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

For more info, look here:

Selecting element by data attribute

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM