Change content of a div using JavaScript

前端 未结 4 1367
萌比男神i
萌比男神i 2020-12-10 04:06

How to dynamically change content of a div using JavaScript?

相关标签:
4条回答
  • 2020-12-10 04:27

    This should do it:

    <div id="foo">Div you want to change</div>
    

    And in JavaScript:

    document.getElementById('foo').innerHTML = 'Your content';
    
    0 讨论(0)
  • 2020-12-10 04:30

    Its worth noting that you can also use innerHTML to include other markup. Also if the DIV des not have an ID you can try using getElementsByTagName.

    Example, to get the first DIV in the document:

    document.getElementsByTagName("div")[0].innerHTML = "<p>This is a <span>new</span> paragraph</p>";
    

    This allows you to loop through multiple DIVs in the document and check other conditions.

    And like they said above, if the DIV has an ID that you know will always be there, then thats better to use:

    document.getElementById("theID").innerHTML = "<p>This is a <span>new</span> paragraph</p>";
    

    Check out Prototype (links below) (or jQuery) in handling this as they make life easier, especially when you get into CSS selectors:

    • http://api.prototypejs.org/dom/dollar.html
    • http://api.prototypejs.org/dom/dollardollar.html
    • http://api.prototypejs.org/dom/element.html#select-class_method
    0 讨论(0)
  • 2020-12-10 04:32

    document.getElementById("divId").innerHTML = "new content!"

    I would recommend using a framework like jQuery though, because chances are you will be doing more things like this later.

    0 讨论(0)
  • 2020-12-10 04:35
    $(document).ready(function(){
    
    $('#btn').click(function(){   
    
        $('#div_content').load('html.page');
    
     });
    });
    
    0 讨论(0)
提交回复
热议问题