using JS to tweak generated menu

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • svendok
    New Member
    • Jun 2010
    • 25

    using JS to tweak generated menu

    I have a menu that's being generated using DHTML. I want to tweak the properties of some nodes (i.e., DIV tags) in it using JavaScript after the fact, but am not succeeding.

    Here's my code.
    Code:
    arr_nodes = document.getElementsByTagName('DIV');
    
    for (i = 0; i < arr_nodes.length; i++) 
    {
    	obj_node = arr_nodes[i];
    	
    	//This DIV is in the source. Change & alert work.
    	if(obj_node.innerHTML=="Test1")
    	{
    			obj_node.innerHTML="Changed";
    			alert(obj_node.innerHTML);
    	}
    	
    	//This DIV is in the generated HTML. Change fails, but alert works.	
    	if(obj_node.innerHTML=="Test2")
    	{
    			obj_node.innerHTML="Changed";
    			alert(obj_node.innerHTML);
    	}
    }
    What do you have to do differently for generated HTML?

    Thanks.
  • phvfl
    Recognized Expert New Member
    • Aug 2007
    • 173

    #2
    The innerHTML property is readonly once an element has been added into the DOM. To change the content the easiest way is to replace the content, this example assumes that there is only one child node of the div
    Code:
    // Get a reference to the DOM node
    var div = document.getElementById('foo');
    
    // Create the new text content
    var newContent = document.createTextNode('bar');
    
    // Replace the existing text node.
    div.replaceChild(newContent, div.childNodes[0]);

    Comment

    • svendok
      New Member
      • Jun 2010
      • 25

      #3
      Originally posted by phvfl
      The innerHTML property is readonly once an element has been added into the DOM. To change the content the easiest way is to replace the content, this example assumes that there is only one child node of the div
      Code:
      // Get a reference to the DOM node
      var div = document.getElementById('foo');
      
      // Create the new text content
      var newContent = document.createTextNode('bar');
      
      // Replace the existing text node.
      div.replaceChild(newContent, div.childNodes[0]);
      Thanks. that's very helpful.

      Comment

      Working...