Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery closest element with an attribute that contains a value

I have some HTML code that looks like this:

<tr id="nbContent_GR1">...</tr>
<tr id="nbContent_GR2">...</tr>
<tr id="nbContent_GR3">...</tr>
<tr id="nbContent_GR4">...</tr>
<tr id="nbContent_GR5">...</tr>
<tr id="nbContent_GR6">...</tr>

Within one of the rows, I want to traverse up the DOM to find the closest element that has an ID attribute that starts with "nbContent_GR". So basically I want to be able to find the parent TR element without knowing its exact ID, just the first one that starts with "nbContent_GR". Is this possible? If so, how would I go about it?

BTW, I'm aware of the closest() and "contains" selectors, just not sure if contains can be used on attribute values or not.

like image 251
Scott Avatar asked Oct 13 '12 23:10

Scott


People also ask

How do you find the element based on a data attribute value?

Answer: Use the CSS Attribute Selector You can use the CSS attribute selectors to find an HTML element based on its data-attribute value using jQuery. The attribute selectors provide a very powerful way to select elements.

What is $$ in jQuery?

$ is another, which is just an alias to jQuery . $$ is not provided by jQuery. It's provided by other libraries, such as Mootools or Prototype.

How get value of data attribute 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 I get the closest div using jQuery?

The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.


3 Answers

Just do:

tr = $(this).closest("[id^='nbContent_GR']");

that will traverse the DOM up until it finds a parent with ID starting with 'nbContent_GR'

like image 53
Nelson Avatar answered Oct 08 '22 08:10

Nelson


.closest('[id^="nbContent_GR"]')
like image 30
RASG Avatar answered Oct 08 '22 08:10

RASG


Two useful pages to look at:

http://api.jquery.com/closest/

http://api.jquery.com/attribute-starts-with-selector/

I think you can combine these for a solution.

From within the TR, find the closest TR. Then use the 'starts with' selector to find an ID which starts with your required value.

E.g.:

$(this).closest("tr").parent().find("id^='nbContent_GR'");
like image 35
sync Avatar answered Oct 08 '22 10:10

sync