View Full Version : Syntax to loop through document using getElementsByTagName - Need direction - Urgent

04-14-2006, 10:46 PM
I have been working on this for a couple of days and I am not getting anywhere. I need to loop through the document, grab particular tags and create a list of the ids in these particular tags. I need to get the id for only the tags that have an id that starts with "pos".

For example, the tags I want to pull out look like:

<div id="pos-RCH" title="RCH"></div>
<div id="pos-SKY" title="SKY"></div>
<div id="pos-LDB" title="LDB"></div>
<div id="pos-PRO" title="PRO"></div>

I need to create a list that would look like: pos-RCH, pos-SKY, pos-LDB, pos-PRO.

I need to make this call as generic as possible because other people will be coding different ids but will have to follow the naming convention of "pos-" for the ids in the div tags.

I am assuming I need to do something like this:

var alldivs = document.getElementsByTagName("div");

for (var i = 0; i < alldivs.length; i++) {
//do something to create this list (pos-RCH, pos-SKY, pos-LDB, pos-PRO)

Please, if anyone can direct me, I would truly appreciate it.

04-14-2006, 11:03 PM
Something like:

<script type="text/javascript">
var posArray = new Array();
var alldivs = document.getElementsByTagName("div");
function getIds(){
for (var i = 0; i < alldivs.length; i++) {
if (alldivs[i].getAttribute('id') != null && alldivs[i].getAttribute('id').match('pos-')) {
posArray[posArray.length] = alldivs[i].getAttribute('id');
alert(posArray); // Just to show the results.

04-14-2006, 11:15 PM
I'd use the RegExp test() method instead.

var alldivs = document.getElementsByTagName("div");
var re = new RegExp('^pos-','i');

for (var i = 0; i < alldivs.length; i++) {
if(alldivs[i].id && re.test(alldivs[i].id)) // add it to the list

More Information. (http://www.google.com/search?q=JavaScript+regexp)

04-17-2006, 02:42 PM
Thanks! I was able to get it to work by using both methods. Thanks so much for your help!

04-18-2006, 09:37 AM
You may do it generic, by using a wildcard to grab all the taged elements

var alltags = document.getElementsByTagName('*')

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum