Search code examples
javascriptjqueryinnerhtml

innerHTML not working in any browser


<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>css demo</title>
</head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
    (function(){
        var html = '<p>';
            html += 'Hello World';
            html += '</p>';

        $(document.body).innerHTML = html;  
        //document.body.innerHTML = html;
    })
</script>
<body>
</body>
</html>

$(document.body).innerHTML = html; // jQuery one is not working either. document.body.innerHTML = html; // normal JS trying to query DOM is not working either.

What's the actually issue here?. I know while using jQuery we don't need to use innerHTML to append the HTML thing, just was trying and learning it out.


Solution

  • you need to get the dom element, $(document.body) returns a jQuery wrapped element which does not have innerHTML property

    $(document.body).get(0).innerHTML = html; 
    

    or simple

    document.body.innerHTML = html; 
    

    using jQuery

    $('body').html(html)
    

    also it looks like the anonymous function is not called

    (function(){
        var html = '<p>';
        html += 'Hello World';
        html += '</p>';
    
        document.body.innerHTML = html;
    })()
    

    if you need to wait for dom ready then

    jQuery(function($){
        var html = '<p>';
        html += 'Hello World';
        html += '</p>';
    
        $('body').html(html)
    })