How to replace innerHTML of a div using jQuery?

前端 未结 13 1693
北恋
北恋 2020-11-22 11:57

How could I achieve the following:

document.all.regTitle.innerHTML = \'Hello World\';

Using jQuery where regTitle is my di

相关标签:
13条回答
  • 2020-11-22 12:29

    you can use either html or text function in jquery to achieve it

    $("#regTitle").html("hello world");
    

    OR

    $("#regTitle").text("hello world");
    
    0 讨论(0)
  • 2020-11-22 12:30

    There are already answers which give how to change Inner HTML of element.

    But I would suggest, you should use some animation like Fade Out/ Fade In to change HTML which gives good effect of changed HTML rather instantly changing inner HTML.

    Use animation to change Inner HTML

    $('#regTitle').fadeOut(500, function() {
        $(this).html('Hello World!').fadeIn(500);
    });
    

    If you have many functions which need this, then you can call common function which changes inner Html.

    function changeInnerHtml(elementPath, newText){
        $(elementPath).fadeOut(500, function() {
            $(this).html(newText).fadeIn(500);
        });
    }
    
    0 讨论(0)
  • 2020-11-22 12:31
    $("#regTitle").html("Hello World");
    
    0 讨论(0)
  • 2020-11-22 12:31

    The html() function can take strings of HTML, and will effectively modify the .innerHTML property.

    $('#regTitle').html('Hello World');
    

    However, the text() function will change the (text) value of the specified element, but keep the html structure.

    $('#regTitle').text('Hello world'); 
    
    0 讨论(0)
  • 2020-11-22 12:31

    Pure JS and Shortest

    Pure JS

    regTitle.innerHTML = 'Hello World'
    

    regTitle.innerHTML = 'Hello World';
    <div id="regTitle"></div>

    Shortest

    $(regTitle).html('Hello World'); 
    

    // note: no quotes around regTitle
    $(regTitle).html('Hello World'); 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div id="regTitle"></div>

    0 讨论(0)
  • 2020-11-22 12:33

    jQuery has few functions which work with text, if you use text() one, it will do the job for you:

    $("#regTitle").text("Hello World");
    

    Also, you can use html() instead, if you have any html tag...

    0 讨论(0)
提交回复
热议问题