Skip to content Skip to sidebar Skip to footer

Finding The Closest, Previous Element With Specific Data Attribute Jquery

This has been troubling me for the passed few hours now. I have a table. Within that table i'm looking for the closest, previous table row with a specific data attribute. I'm doing

Solution 1:

.prev only returns the immediately previous element, it doesn't keep looking for the nearest element that matches the selector. Use .prevAll to find all the elements matching a selector, and then use .first() to narrow it down to the first one, which is the nearest. And if you want to search for a specific data-menu-level attribute, you have to put that in the selector; calling .data("menu-level", 1) sets the attribute, it doesn't search for it.

if (menuLevel == 2) {
    var findAboveRowName = $(".menu-table-rows[data-menu-nesting='" + newIndex + "']").prevAll(".menu-table-rows[data-menu-level=1]").first().data("menu-name");
    alert(findAboveRowName);    
}

Post a Comment for "Finding The Closest, Previous Element With Specific Data Attribute Jquery"