2015-08-08 85 views
1

有沒有像CSS任何方式,我們可以用JavaScript改變顏色的標籤,我試過的getElementsByTagName但沒有任何反應。的getElementsByTagName是不會改變顏色

我試圖尋找谷歌,但遺憾的是沒有找到,這就是爲什麼我問這個基本的JavaScript問題在這裏,感謝提前你的答案......

此代碼是不工作...

HTML :

<p id="demo"> test test test test test</p> 

<span id="demoz"> test2 test2 test2 test2 test2</span> 

的Javascript:

document.getElementById('demo').style.background = "green"; 

document.getElementsByTagName('span').style.background = "green"; 

的jsfiddle:

http://jsfiddle.net/3j0vokLd/

+0

這是因爲它會返回元件一樣的陣列'getElementsByClassName方法()''嘗試document.getElementsByTagName( '跨度')[0] = .style.background 「綠色」;' – NewToJS

回答

4

這是因爲​​將產生類似陣列的對象。

要改變這個函數返回每個(跨度)元素的背景顏色,你會遍歷返回數組過(類似的對象):

var spanElements = document.getElementsByTagName('span'); 

for (var i = 0; i < spanElements.length; i++) { 
    spanElements[i].style.background = 'green'; 
} 

See the updated JSFiddle

或者,如果你是隻是針對單個span元素,返回數組中的第一個,你可以這樣做:

document.getElementsByTagName('span')[0].style.background = 'green'; 
+1

大概應該是'.backgroundColor',不只是'.background' – Pointy

+0

感謝您的幫助 –

2

它返回一個NodeList:(?好,你可以在一個頁面上的多個span標籤,右)

document.getElementsByTagName('span')[0].style.background = "green"; 
+4

我相信索引應該是0.數組中的第一個也是唯一的元素。 – csbarnes

+0

好點,固定:) – beautifulcoder

+1

當然,如果沒有在頁面上的任何跨度,那麼當您試圖訪問數組的索引,這將崩潰。 – Spudley

1

是 - 檢查出來:

http://jsfiddle.net/gratiafide/gj0g5ysr/

var x = document.getElementsByTagName("SPAN"); 
var i; 
for (i = 0; i < x.length; i++) { 
    x[i].style.backgroundColor = "red"; 
} 

的getElementsByTagName返回一個集合,這是像陣列

+0

它不是像數組...它實際上數組 – Tushar

+0

也許吧,但他們只在這裏稱之爲集合,這有時意味着有可能區別:http:// www。w3schools.com/jsref/met_document_getelementsbytagname.asp – user3089840

+4

@ user3089840 @TusharGupta:請勿使用[w3schools](http://www.w3fools.com/),請使用[MDN](https://developer.mozilla.org/ EN-US /)。您會注意到['getElementsByTagName'](https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName)會返回['HTMLCollection'](https://developer.mozilla)。 org/en-US/docs/Web/API/HTMLCollection),它不是['Array'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array ),而是一個類似數組的對象。 – Oka

1

嘗試利用document.querySelector()具有選擇"span[id=demoz"])指定具有屬性span元件id="demoz"設置background

document.getElementById("demo").style.background = "green"; 
 

 
document.querySelector("span[id=demoz]").style.background = "green";
<p id="demo"> test test test test test</p> 
 

 
<span id="demoz"> test2 test2 test2 test2 test2</span>

的jsfiddle http://jsfiddle.net/3j0vokLd/3/

+0

不錯。非常簡潔。 – user3089840

+0

感謝您的幫助 –