How to replace innerHTML of a div using jQuery?

前端 未结 13 1692
北恋
北恋 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:17
    $("#regTitle")[0].innerHTML = 'Hello World';
    
    0 讨论(0)
  • 2020-11-22 12:18

    Here is your answer:

    //This is the setter of the innerHTML property in jQuery
    $('#regTitle').html('Hello World');
    
    //This is the getter of the innerHTML property in jQuery
    var helloWorld = $('#regTitle').html();
    
    0 讨论(0)
  • 2020-11-22 12:18

    Just to add some performance insights.

    A few years ago I had a project, where we had issues trying to set a large HTML / Text to various HTML elements.

    It appeared, that "recreating" the element and injecting it to the DOM was way faster than any of the suggested methods to update the DOM content.

    So something like:

    var text = "very big content";
    $("#regTitle").remove();
    $("<div id='regTitle'>" + text + "</div>").appendTo("body");
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    Should get you a better performance. I haven't recently tried to measure that (browsers should be clever these days), but if you're looking for performance it may help.

    The downside is that you will have more work to keep the DOM and the references in your scripts pointing to the right object.

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

    If you instead have a jQuery object you want to render instead of the existing content: Then just reset the content and append the new.

    var itemtoReplaceContentOf = $('#regTitle');
    itemtoReplaceContentOf.html('');
    newcontent.appendTo(itemtoReplaceContentOf);
    

    Or:

    $('#regTitle').empty().append(newcontent);
    
    0 讨论(0)
  • 2020-11-22 12:26

    jQuery's .html() can be used for setting and getting the contents of matched non empty elements (innerHTML).

    var contents = $(element).html();
    $(element).html("insert content into element");
    
    0 讨论(0)
  • 2020-11-22 12:27

    Answer:

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

    Explanation:

    $ is equivalent to jQuery. Both represent the same object in the jQuery library. The "#regTitle" inside the parenthesis is called the selector which is used by the jQuery library to identify which element(s) of the html DOM (Document Object Model) you want to apply code to. The # before regTitle is telling jQuery that regTitle is the id of an element inside the DOM.

    From there, the dot notation is used to call the html function which replaces the inner html with whatever parameter you place in-between the parenthesis, which in this case is 'Hello World'.

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