Setting innerHTML: Why won't it update the DOM?

前端 未结 5 926
伪装坚强ぢ
伪装坚强ぢ 2020-11-29 08:37

Wondering why I can\'t get document.getElementById(\"my_div\").innerHTML to update the DOM when I re-assign the variable. For example:

相关标签:
5条回答
  • 2020-11-29 09:01

    you need to reassign the element after setting innerHTML/outerHTML:

    let indexInParent=[].slice.call(elem.parentElement.children).indexOf(elem);
    elem.innerHTML=innerHTML;
    elem=elem.parentElement.children[indexInParent];
    
    0 讨论(0)
  • 2020-11-29 09:10

    For future googlers my problem was that I was calling the plural elements.

    document.getElementsByClassName(‘class’).innerHTML

    So it returned an Array not a single element. I changed it to the singular.

    document.getElementByClassName(‘class’).innerHTML

    That made it so I could update the innerHTML value.

    0 讨论(0)
  • 2020-11-29 09:11

    innerHTML evaluates to a string. I'm not sure why you would expect anything different. Consider this:

    var a = 'foo'; // now a = 'foo'
    var b = a; // now a = 'foo', b = 'foo'
    b = 'bar'; // now a = 'foo', b = 'bar'
    

    Re-assigning b doesn't change a.

    Edited to add: In case it's not clear from the above, if you want to change innerHTML, you can just assign to it directly:

    document.getElementById("my_div").innerHTML = "Hello";
    

    You don't need, and can't use, an intermediary variable.

    0 讨论(0)
  • 2020-11-29 09:23

    you should set the innerHTML value like

     var myDivValue = document.getElementById("my_div").innerHTML = "Hello";
    
    0 讨论(0)
  • 2020-11-29 09:24
     var myDivValue = document.getElementById("my_div").innerHTML;
    

    stores the value of innerHTML, innerHTML contains a string value, not an object. So no reference to the elem is possible. You must to store directly the object to modify its properties.

    var myDiVElem = document.getElementById("my_div");
    myDiVElem.innerHTML = 'Hello'; // this makes the change
    
    0 讨论(0)
提交回复
热议问题