Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Assigning Numbered IDs

Status
Not open for further replies.

akvbroek

Technical User
Jan 23, 2009
8
US
I have a long list and the person that will be maintaining the site is NOT savvy at anything. So, I would like to write a function that will loop through all the UL elements and add an ID called "content#" where # starts at 0 and increases by 1 each time.

I have tried a number of things with no success.

The reason I would like this to be done by javascript and not manually is that the list is VERY long and the id will need to be added roughly 270 times, if she misses even one number, than the javascript that uses that id will fail to work.

Here is the basic idea, but it doesn't work:

Code:
function addid() {
var g = document.getElementsByTagName('ul');
for(var i=0; i<g.length; i++) {g.id = 'content'+i;}
}

(Yeah, I know I suck at javascript [neutral], so don't laugh if that is a feeble attempt.)

Thanks in advance for any help!!
 
You're almost there:

Code:
function addid() {
   var g = document.getElementsByTagName('ul');
   for(var i=0; i<g.length; i++) { g[!][i][/!].id = 'content' + i; }
}

Hope this helps,
Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 
Thanks that helped!!

Now, I am also trying to filter it by items that have a certain class. I have tried it and it doesn't seem to work.

Anymore brilliant ideas? :)

This is what I have (and various variations of)...

Code:
function addid() {
   var g = document.getElementsByTagName('ul');
   for(var i=0; i<g.length; i++) { if(g[i].class == 'tree') {g[i].id = 'content' + i; }}
}

???
 
Ok, scratch that...

I can filter it by name (code at end of post), which works, but it does this (obviously not real code but the general gist):

Code:
<ul name="tree" id="content1">
<ul>
<ul>
<ul name="tree" id="content4">
<ul>
<ul name="tree" id="content6">

When I want...

Code:
<ul name="tree" id="content1">
<ul>
<ul>
<ul name="tree" id="content2">
<ul>
<ul name="tree" id="content3">

Any ideas? THANKS!!


Filter by name:
Code:
   var g = document.getElementsByTagName('ul');
   for(var i=0; i<g.length; i++) { if(g[i].name == 'tree') { g[i].id = 'content' + i; }}
 
ha, I am a fool. :)

Ok I solved this myself and in case anyone wanders through and wonders how...

I simply needed to simplify and use getElementsByName from the get go rather than by TagName and then trying to filter through those.

Sheesh...

Thanks anyway!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top