开发者

Jquery select all elements containing text in ID

开发者 https://www.devze.com 2023-01-26 03:37 出处:网络
I have the following code: var aggrH开发者_运维技巧TML = $(\'TBODY#aggr > tr > td > table > tbody > tr > td > nobr > b\');

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').

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号