Add a class name to each element and use document.querySelectorAll() with the CSS-selector for class to retrieve the list of all elements with that class. Then iterate over the elements using NodeList.forEach() and passing it that function as a callback.
See this demonstrated in the example below. The commas will be added when the user clicks the button containing the text 'Add Commas'.
function addCommas() {
//get a list of elements with class attribute containing 'portfolio_price'
var priceContainers = document.querySelectorAll(".portfolio_price");
//run the function on each element in the list
priceContainers.forEach(function(priceContainer) {
var x = priceContainer.innerHTML;
var len = x.length;
var y = x.substring(0, len - 3) + "," + x.substring(len - 3);
priceContainer.innerHTML = y;
});
}
document.addEventListener('DOMContentLoaded', function() {
var button = document.getElementById('addCommas');
button.addEventListener('click', addCommas);
});
<div class="portfolio_price" id="price_1">10.20</div>
<div class="portfolio_price" id="price_2">10.20</div>
<button id="addCommas">Add Commas</button>
As Luvn Jesus suggests, you could use jQuery
or a similar library to take advantage of helper functions. For example,
var priceContainers = document.querySelectorAll(".portfolio_price");
can be simplified to
var priceContainers = $(".portfolio_price");