Reputation: 231
How can i populate multiple id tags simultaneously.
On my page i have id tags starting with "total_" phrase, like total_1, total_2 etc., is there a way by which i can populate each of them on a single click in javascript.
Should i use regex or parser.
Any help will be highly appreciated.
Thank you.
Upvotes: 0
Views: 186
Reputation: 700660
If you know how many there are, you can simply loop through the numbers:
for (var i=1; i<=10; i++) {
document.getElementById('total_'+i).innerHTML = 'text';
}
If you are using jQuery, you can loop through all elements of a specific type, and look for the id. It's less efficient, but more flexible. It will work even if the numbers are not contiguous:
$('div').filter(this.id && this.id.substr(0,6) == 'total_').html('text');
(You can of course loop through elements without a library like jQuery, but then it's a bit more code...)
Upvotes: 3
Reputation: 58979
for(var i=1; true; i++){
var elm = document.getElementById("total_"+i);
if(elm == undefined){
break;
}
elm.innerHTML = "Some text here";
}
Using jQuery you can do the following:
$("div[id^='total_']").html("Some text Here");
Upvotes: 4