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.
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.
Share Improve this question asked Oct 13, 2012 at 23:28 ScottScott 13.9k20 gold badges97 silver badges156 bronze badges 1- Sorry, didn't understand what you asked. – The Alpha Commented Oct 13, 2012 at 23:32
4 Answers
Reset to default 15Just do:
tr = $(this).closest("[id^='nbContent_GR']");
that will traverse the DOM up until it finds a parent with ID starting with 'nbContent_GR'
.closest('[id^="nbContent_GR"]')
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'");
This may be late but for those of you who like me want it a bit different way, I figured out this way.
$(document).on('click', '.btn-info', function() {
var cardId = $(this).closest(".cardClass").attr("id");
alert(cardId);
console.log(cardId);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
<div id="card1" class="cardClass">
<button type="button" class="btn btn-info"></button>
</div>
<div id="card2" class="cardClass">
<button type="button" class="btn btn-info"></button>
</div>
<div id="card3" class="cardClass">
<button type="button" class="btn btn-info"></button>
</div>
<div id="cardn" class="cardClass">
<button type="button" class="btn btn-info"></button>
</div>
</div>