[JavaScript]複数のセレクタを指定し対象を絞り込む
書式
document.querySelectorAll(“セレクタ1 セレクタ2")
使用例
<div id="show">
<span class="cftB">tokyo</span>
</div>
<input type="button" value="変更" />
<script>
function change() {
/*セレクタを空白区切りで2つ指定*/
const res = document.querySelectorAll("#show .cftB");
// forEachで要素をループ
res.forEach(function (x) {
// ノードのテキストの内容を判定
if (x.textContent === "tokyo") {
x.textContent = "東京";
} else {
x.textContent = "東京以外";
}
});
}
</script>
結果
「変更」ボタンを押下すると、「tokyo」を「東京」に変換する