0

I need your help :) !

I have a page where there are a lot of tags and I have to retrieve in an array all id who begin by td_

I can not use the jQuery framework... Else there will be more easy...

Do you how I can do it ?

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
Geoffrey
  • 5
  • 5
  • In “pure” JS, get all TD elements using getElementsByTagName, loop over those, and check their id with indexOf - and if it checks out, put them into an array. – CBroe Jul 03 '13 at 15:37

2 Answers2

1

You can use the querySelector:

elementList = document.querySelectorAll('td[id^=td_]');
stackErr
  • 4,130
  • 3
  • 24
  • 48
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++]));
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • Please consider to comment on downvote... – A. Wolff Jul 03 '13 at 15:47
  • It is extremely inefficient to search for attribute only, as it forces JS to search all attributes of every element on the page; use `'td[id^="td_"]'` instead. And what's the point of `arr` and the `for` loop when `nodeList` is already an array? – Derek Henderson Jul 03 '13 at 15:47
  • Please give us a moment to type the comment on the downvote! (Downvote removed and comment amended, as the reason for the downvote was the malformed selector, which you've fixed.) – Derek Henderson Jul 03 '13 at 15:48
  • @DerekHenderson thx for the input. Typo fixed. OP stated: << there are a lot of tags and I have to retrieve in an array all id who begin by td_ >> So i suppose there are not only TDs – A. Wolff Jul 03 '13 at 15:49
  • True, but then his title also makes clear that he is targeting TDs. ;) – Derek Henderson Jul 03 '13 at 15:50
  • 1
    @DerekHenderson and OP still stated he wants array, querySelectorAll returns a prototype nodeList. But i'm quite sure OP doesn't really know what he was expecting for ;) – A. Wolff Jul 03 '13 at 15:50
  • I didn't realise that about `querySelectorAll`. I assumed it returned an array. Thank you for that clarification. – Derek Henderson Jul 03 '13 at 15:54