Click here to Skip to main content
15,892,965 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Can you tell me how would you add ids to a dynamically generated table. Right now I can get the length of the element by its class name and I don't know how to append it on the fly


-SanSel
Posted
Comments
Sergey Alexandrovich Kryukov 22-Jan-12 14:41pm    
Do you need it to use getElementById later on?
--SA

1 solution

First of all, if you mean to add the element attribute id to some automatically generated elements, you can always do it, I'm not sure this is the best technique you can use. First of all, why did not you generate the required IDs when you generated the table? Secondly, do you need to use document.getElementById? Is that your purpose? Instead, you could keep the references to all elements you need in memory and use it later. I hope you also know that with JavaScript, you can add any property to any object at any time. In other words, as you auto-generate some elements and add them to DOM, you can reference them outside DOM as general-purpose JavaScript objects. Just some food for thought.

Now, if you really need to use the id attribute of a DOM element, I would advise to use jQuery and the method .attr(). Please see:
http://api.jquery.com/attr/[^],
http://jquery.com/[^],
http://en.wikipedia.org/wiki/JQuery[^].

Using jQuery really makes such things easy to implement and maintain; and the code looks very compact. Also, the library addresses browser compatibility problems. I highly recommend using this library when it comes to using JavaScript in browsers.

—SA
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 23-Jan-12 0:20am    
You can find appending and other similar operations in Manipulation section of the documentation:
http://api.jquery.com/category/manipulation/
Check DOM insertion.
--SA
SanPra66 23-Jan-12 10:24am    
After assigning the ids how can I access them outside of the script in my html document. CAn you walk me through this please
SanPra66 23-Jan-12 10:33am    
I will explain what I am trying to achieve.

Basically I want to create rows of table using the jquery's sortable feature and I want to have a serial number outside of this table so that when the user moves row1 to row 3 the s.no will stay intact since it is outside the generated row. The serial number should be in sync with the size of the generated number of rows

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900