0

Im developing a script for dynamically creating html table structure so that from the input that has been given to the function it will fetch the values one by one and will create the structure. My problem is i want to add attributes to the elements created. sample code attached.

with( window['o' + elementname]){
 for(j=0;j<attrs.length;j++)
 {
 if(attrs[j].indexOf("=")!=-1){
var attr1={}
attr1=attrs[j]
attr1=attr1.split("=")
[B] window[attr1[0]]=attr1[1];[/B]
}
 }}

here the element name will be get from the parameters passed to the function. i want to verify whether the line in bold is correct or not coz the id is not updated in output.

2
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by Taywin
0

Hmm... I'm wrong. You could change the ID, but it is not a good idea. You could, however, clone the element and reassign a new ID, then remove the old element and add the new element to the same place.

Well, if you want, you could actually use document.getElementById(elementID) instead of hard code to search for an element ID property which may or may not at the location you are trying to change.

var el = document.getElementById(elemID)
el.id = "newID"

PS: It is dangerous to change ID of elements with JavaScript because the original element ID is no longer existed. As a result, it could cause difficulty in maintenance for the page.

Edited by Taywin: n/a

0

here the value of both attribute name and value will be passed as parameter. how to accomplish that?

0

Yes, you could pass any value you want to the function. However, using "name" is a bit tricky in older and newer browser. Because the "name" attribute allows duplications, you have to distinguish which element you want to change if you do not want to change all of them.

// use ID
function updateID(elemID, val) {
  var el = document.getElementById(elemID)
  if (el) {  // exists
    el.id = val
  }
}

// use name, newer browser
function updateID(elemName, val) {
  var els = document.getElementsByName(elemName)
  for (var i=0; i<els.length; i++) {
    if (condition_to_find_the_element_you_want) {
      els[i].id = val
      break
    }
  }
}

// use name, older browser
function updateID(elemName, tagName, val) {
  var els = document.getElementsByTagName(tagName)
  for (var i=0; i<els.length; i++) {
    if (els[i].getAttribute("name")==elemName) {
      if (condition_to_find_the_element_you_want) {
        els[i].id = val
        break
      }
    }
  }
}

The getProperty() (or getAttribute()) and setProperty() (or setAttribute()) may be used, but they are still not perfect (contains bug). However, the "get" functionality is still maneuverable, so it is OK to use. The "set" functionality is the one that you could use for your own risk.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.