Jquery select all elements containing text in ID
I have the following code:
var aggrH开发者_运维技巧TML = $('TBODY#aggr > tr > td > table > tbody > tr > td > nobr > b');
var aggrText = aggrHTML.text();
var newText = "Total" + aggrText.substring(3);
aggrHTML.html(newText);
What I would like to do is alter the above so I select all elements whose id contain 'aggr'.
Many Thanks, Nav
var aggrHTML = $('TBODY[id*=aggr] > tr > td > table > tbody > tr > td > nobr > b');
var aggrText = aggrHTML.text();
var newText = "Total" + aggrText.substring(3);
aggrHTML.html(newText);
Simplest way to achieve that is
var aggrHTML = $("[id*=aggr]");
var aggrText = aggrHTML.text();
var newText = "Total" + aggrText.substring(3);
aggrHTML.html(newText);
If by "all elements" you mean all DOM elements of course.
All the above answers will work to an extent, but your snippet suggests that you want each of the elements selected to be updated individually. The code in the other answers will set each of them to the same value as the first one.
You need to use the callback signature of .html()
:
$('TBODY[id*=aggr] > tr > td > table > tbody > tr > td > nobr > b').html(
function(idx, oldHTML) {
return 'Total' + oldHTML.substring(3);
}
);
This will update each b
element individually.
One more piece of advice: put ids or classes on elements lower down the DOM. This would simplify your selection significantly, speeding up the execution and writing of your code. In this case, for instance, you could put a class aggrchild
on your lowest td
elements and do a selection like $('td.aggrchild b')
.
精彩评论