今回はWordPressのカスタマイズを行なっている際に、商品の値段がカンマなしで表示されているので、3桁目と4桁目の間にカンマを自動的に挿入するJavaスクリプトを用意したので皆様にコードを共有いたします。
function addCommaToPrices() {
// 'price-coma'のすべての項目を検索する。
const priceElements = document.querySelectorAll('.price-coma');
// 各要素を繰り返し処理する
priceElements.forEach(function(element) {
// 要素のテキスト内容を取得する
let priceText = element.textContent;
// priceTextの長さが4桁以上でカンマが必要かを確認する。
if (priceText.length >= 3) {
// 右から3桁目と4桁目にカンマを入れる。
let position = priceText.length - 3;
priceText = priceText.slice(0, position) + ',' + priceText.slice(position);
// 要素のテキスト・コンテンツを更新する
element.textContent = priceText;
}
});
}
// 変更を適用するために関数を実行する
// DOMが完全にロードされた後にこの関数を実行すると、要素を見つけることができる:
document.addEventListener('DOMContentLoaded', addCommaToPrices);
最終更新日: 2025-12-05