如何在 JavaScript 中按類獲取元素? - How to Get Element By Class in JavaScript?

問題:

I want to replace the contents within a html element so I'm using the following function for that:我想替換 html 元素中的內容,因此我爲此使用了以下函數:

function ReplaceContentInContainer(id,content) {
   var container = document.getElementById(id);
   container.innerHTML = content;
}

ReplaceContentInContainer('box','This is the replacement text');

<div id='box'></div>

The above works great but the problem is I have more than one html element on a page that I want to replace the contents of.上面的效果很好,但問題是我想要替換其中的內容的頁面上有多個 html 元素。 So I can't use ids but classes instead.所以我不能使用 id 而是使用類。 I have been told that javascript does not support any type of inbuilt get element by class function.有人告訴我 javascript 不支持任何類型的按類函數的內置 get 元素。 So how can the above code be revised to make it work with classes instead of ids?那麼如何修改上面的代碼以使其適用於類而不是 id 呢?

PS I don't want to use jQuery for this. PS我不想爲此使用jQuery。


解決方案:

參考一: https://stackoom.com/question/FyqO
參考二: How to Get Element By Class in JavaScript?
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章