Reputation: 1981
I need to change the class of a span based upon the existence of a table, further on down the html structure.
Basically, the html is built dynamically, using code behind on a c# page, which is then appended to div tag. This all works perfectly, fine, but now I have a need to change the class value of a span tag, if the presence of table is found.
So, the structure looks something like this:
<tr>
<td><span class="badge badge-default"></td>
<td>some stuff</td>
<td><table id="hitTable"></tr>
</tr>
In the above example the second td after the span, does contain a table with the id of hitTable, in this case I need use JQuery to change the class of span, to badge badge-danger.
I'm not sure, how to traverse up, once I've identified the table.
This code will change any spans, within the table, but how do i change the first span outside of the table?
$('table[id^="hit"] span').addClass('badge badge-danger');
Upvotes: 0
Views: 970
Reputation: 207527
Seems weird you do not just add the class when you are dynamically building the table on the server. BUT if you want to do it on the client, you need to select the table and work your way upwards and back down.
$('table[id^="hit"]') //select the hit table
.closest("tr") //find closest tr that contains the table
.find("> td > span") //find the span in a child td
.addClass('badge-danger'); //add the class
Other way would be to select the tr and use .has()
to find the trs with the table, than select the span.
Upvotes: 1
Reputation: 302
You can use jQuery .lenght in order to check if table#hitTable exists.
var $object = $('#hitTable');
if($object.length) {
$('span.badge').addClass('badge-danger');
}
http://jsfiddle.net/lddz/9hob9t5k/3/
Upvotes: 1