Skip to content Skip to sidebar Skip to footer

Get Value From Where Matches Text

With a system that I use you can create custom fields. These fields all have the same html and css. Now I would like to get the value td where the th is week. Now I use: var wee

Solution 1:

Var 1:

var week=0;
$('table tr td').each(function(){
	if($(this).prev().text()=='Week'){
		week=parseInt($(this).text(), 10);
	}
});
console.log(week);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><table><tr><thclass="bug-custom-field category">Name</th><tdclass="bug-custom-field"colspan="5">Test</td></tr><tr><thclass="bug-custom-field category">Week</th><tdclass="bug-custom-field"colspan="5">23</td></tr></table>

Var 2:

var week = $('table').find('td.bug-custom-field:last').text();
console.log(week);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><table><tr><thclass="bug-custom-field category">Name</th><tdclass="bug-custom-field"colspan="5">Test</td></tr><tr><thclass="bug-custom-field category">Week</th><tdclass="bug-custom-field"colspan="5">23</td></tr></table>

Solution 2:

You already have most of the details you need. Once you have the th the most robust solution is to go up to the row and then use find to find the td. The alternative is a simple .next() but is more likely to break if the layout changes.

var th = $("th.bug-custom-field.category:contains('Week')")
var row = $(th).closest("tr");
var week = $(row).find('td.bug-custom-field:last').text();

var weekTH = $("th.bug-custom-field.category:contains('Week')")
var weekTR = $(weekTH).closest("tr");
var weekTD = $(weekTR).find('td.bug-custom-field:last');
var week = $(weekTD).text();
console.log(week);
th { text-align:left; }
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><table><tr><thclass="bug-custom-field category">Name</th><tdclass="bug-custom-field"colspan="5">Test</td></tr><tr><thclass="bug-custom-field category">Week</th><tdclass="bug-custom-field"colspan="5">23</td></tr></table>

Post a Comment for "Get Value From Where Matches Text"