![](/img/trans.png)
[英]Javascript: How to get an element by ID then add/place the element into an inline style
[英]how to set style for multiple id element javascript
我正在使用這樣的代碼:
document.getElementById('one').style.color = 'red';
document.getElementById('two').style.backgroundColor= 'blue';
.......
document.getElementById('another').style.fontSize= '20px';
是否有一種通用方法來為多個id元素設置樣式,如下所示(如jQuery)?
document.getElementById('one').add('two').add('three').style.color = 'red';
或者,我該怎么做?
您不能一次在javascript中選擇多個ID。 您可以通過指定相同的類名來實現。
[ 'one', 'two', 'three' ].forEach(function( id ) {
document.getElementById( id ).style.color = "red";
});
您可以使用jQuery
$("input").css('color', 'red');
您也可以將類添加到要更改的目標dom元素中,而不是選擇所有輸入元素。 例如:
<input id="one" class="whatever" ... etc>
<input id="two" class="whatever" ... etc>
<input id="three" class="whatever" ... etc>
並使用此javascript更改它們
$(".whatever").css('color', 'red');
w3schools或jQuery API文檔中有關選擇器的更多詳細信息
通過使用CSS來實現。 為以下每個元素設置相同的類:
<div id="one" class="class1">text</div>
<div id="two" class="class1">text</div>
<div id="three" class="class1">text</div>
CSS:
.class1 { color: blue }
然后使用JQuery在Javascript中對其進行更改,例如:
$('.class1').css({"color":"blue"});
它更有效,更易於理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.