开发者

assigning the id in html through the javascript DOM concept

<body>
<input type="button" value="ADD" onClick="add()">
<table id="myTable">

</table>
<table id="myTable2">

</table>
<table id="myTable3">

</table>
</body>

In the above Code I am creating one table dynamically from the programming part, based on the result which I get.

My question, How can i give the id part in the table dynamically?

ie table id="myTable3" ---> table3 is given for the 3rd row element

2) table2 is given for the 2nd row element

Since we cant have same id in the same HTML so i am creating sequentially and assigning as id

Can any one su开发者_运维技巧ggest with some sample javascript code about assigning the id dynamically. So that I can have a better control later


var  table=document.createElement("table"); 
table.setAttribute("id", "table3");
parent.appendChild(table);

where parent is the container element of the table.You can declare a global counter and use its value to assign the id every time you dynamically create a table


In order to this you only need one simple DOM traversal function. getElementsByTagName.

You can then create an all purpose function that loops through your elements and adds the id.

function addIds(container, elName, prefix){
    // get the container
    var container=document.getElementById(container);
    // get tables
    var tables=container.getElementsByTagName(elName);
    // loop through tables
    for(var i=0;i<tables.length;i++)
        // add ids
        tables[i].id=prefix+(i+1);
}

Since I doubt you want to affect ALL elements in your page, I have created this function that takes a container and then looks inside it for elements with your specified tag and then adds ids to them with a prefix.

Here's an example of it in action on jsfiddle.


var tables = document.getElementsByTagName('table');

for (var i =0; i < tables.length; i++){
  tables[i].id = "table"+i;
}

now your table id will be serialized

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜