2013-07-03 14 views
0

我需要你的幫助:)!如何檢索所有td的id在td_開始在JavaScript

我在那裏有很多的標籤頁和我有一個數組來檢索誰首先td_

我不能使用jQuery框架所有ID ...否則會有更多的方便。 ..

你是怎麼做到的?

+0

在「純」 JS,得到使用的getElementsByTagName,環比那些所有TD元素,並檢查它們的ID與的indexOf - 如果它檢出,把它們放入一個數組中。 – CBroe

回答

1

可以使用querySelector:

elementList = document.querySelectorAll('td[id^=td_]'); 
+0

非常感謝!此代碼正常工作 – Geoffrey

1

DEMO

var nodeList = document.querySelectorAll('[id^=td_]'); // or if only TDs are tergated use: 'td[id^=td_]' instead {thx Derek} 
var arr = []; // Will hold the array of Node's 
for (var i = 0, ll = nodeList.length; i < ll; arr.push(nodeList[i++])); 
+0

請考慮對downvote發表評論... –

+0

僅搜索屬性的效率非常低,因爲它會強制JS搜索頁面上每個元素的所有屬性;改用'td [id^='td _「]''。當'nodeList'已經是一個數組時'arr'和'for'循環有什麼關係? –

+0

請給我們一點時間在downvote上輸入評論! (Downvote刪除和評論修正,作爲downvote的原因是畸形的選擇,你已經修復。) –