Skip navigation
Currently Being Moderated

JS -- XML Question - Can I add attributes using Javascript?

Jul 30, 2012 2:26 PM

Tags: #javascript #xml #attributes

I want to add an attribute to an element tag, but I don't see how to do it programmatically. Is it possible? Also, is there a way to name an element tag dynamically? For example:

 

The way to add a child element is to either use the appendChild method like this:

 

XMLObject.appendChild(<childElement/>);
XMLObject.childElement= "something";

 

or just add it like this:

 

XMLObject.childElement = "something";

 

Right? (Side Question: Is there a difference between these two methods?).

 

What I want to do is to either add a dynamic attribute to a statically named child, or to create a dynamically named child.

 

I haven't been able to figure this out myself. Any ideas?

 
Replies
  • Currently Being Moderated
    Jul 30, 2012 5:09 PM   in reply to lanejd

    Maybe have a look at Mozilla's E4X tutorial: https://developer.mozilla.org/en/E4X_Tutorial/

     

    There's no need for eval() here. (There usually isn't.) Use:

     

    XMLObject.appendChild(<{nameReference}/>);
    

     

    To add an attribute, you can just use:

     

    XMLObject.@new_att = "the value";
    

     

    Jeff

     
    |
    Mark as:
  • Currently Being Moderated
    Jul 30, 2012 11:03 PM   in reply to absqua
    XMLObject["@new_att"] = "the value"; 

     

    With a slight variation the attribute name can also be specified as string, see above.

    To remove the attribute, delete it.

    delete XMLObject["@new_att"]; 


    Dirk

     
    |
    Mark as:

More Like This

  • Retrieving data ...

Bookmarked By (0)

Answers + Points = Status

  • 10 points awarded for Correct Answers
  • 5 points awarded for Helpful Answers
  • 10,000+ points
  • 1,001-10,000 points
  • 501-1,000 points
  • 5-500 points