Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery data attribute selector for closest parent

My code have data attribute set for many elements (Not For All Elements) in below manner.

  1. <div id='dvStorage' data-testing='storage_div'>

And, for some of the elements (Not For All Elements) data attribute is set with below approach.

  1. $("#ElementID").data("testing", "data value");

Now, the problem comes. When any button on the document is clicked, I need to find its parent having data attribute (testing) is set. As mentioned, all elements do not have data attribute, so I need to travese upwards in the hierarchy until the expected element is found.

For #1 approach, $("#buttonID").closest("[data-testing]") works. But not for #2 approach.

For #2 approach, I need to iterate through button parents() and verify if it has .data("testing") or not. I need to avoid this iteration. And have one common approach that works for #1 and #2.

Here, it is not required to verify value of data-testing, but to get the first parent in hierarchy having "testing" set as its data attribute.

Thanks in advance.

JSFIDDLE Demo

like image 225
DevD Avatar asked Apr 10 '15 05:04

DevD


People also ask

How do I find a specific parent in jQuery?

The parent() method returns the direct parent element of the selected element. The DOM tree: This method only traverse a single level up the DOM tree. To traverse all the way up to the document's root element (to return grandparents or other ancestors), use the parents() or the parentsUntil() method.

How get data attribute value in jQuery?

To retrieve a data-* attribute value as an unconverted string, use the attr() method. Since jQuery 1.6, dashes in data-* attribute names have been processed in alignment with the HTML dataset API.

How do you select an element by data?

Use the querySelector method to get an element by data attribute, e.g. document. querySelector('[data-id="box1"]') . The querySelector method returns the first element that matches the provided selector or null if no element matches the selector in the document.


2 Answers

You only have two choices:

As you mentioned in the first choice, you have to iterate through all of the elements because $("#ElementID").data("testing", "data value"); will NOT update the attribute data-testing, because the value is stored internally in the DOM.

The second method is to provide add another class that can be used in the selector:

$("#ElementID").data("testing", "data value").addClass("has-testing");

Thus your new selector would be:

$("#buttonID").closest("[data-testing], .has-testing");

JS Fiddle Example

like image 54
Erik Philips Avatar answered Oct 25 '22 10:10

Erik Philips


try this (work for #2): data-selector

e.g: $('[data-testing] , :data(testing)')
like image 39
MJ Vakili Avatar answered Oct 25 '22 10:10

MJ Vakili