Difference between Jquery.Append() and Jquery.Html()

Asked

Viewed 381 times

0

Today doing content manipulation of a modal came to mind two possibilities

$('div').append('Olá mundo!');

Or else:

$('div').html('Olá mundo!');

But I don’t know exactly what the ideal would be Even though I knew you’d both see me.

My question is in what context should I use one or the other? What is the difference?

3 answers

4


Using the function append you add HTML code as the last child of the parent element. Let’s take the following example:

<div>
    <p>Hello World</p>
</div>

When executing the instruction: $('div').append('Olá mundo!'); the result is as follows:

<div>
    <p>Hello World</p>
    "Olá Mundo!"
</div>

Using the function html you overwrite all the HTML contained in the parent element.

<div>
    <p>Hello World</p>
</div>

After using the function $('div').html('Olá mundo!'); the expected result is as follows::

<div>
    "Olá mundo!"
</div>

1

.append() will include the content(or DOM object) at the end of the context element in question, while .html() will overwrite the entire content within the context element in question with the new value passed as method parameter. So when to use one or the other, one should think about the desired result: if you only want to include a new content to any element should be used .append(), when you want to replace you should use .html()

  • I think with jquery the DOM is always overwritten, the difference is that with the append() it overcoats keeping the previous one and adding a new one, and with the html() it overwrites, excluding the previous

  • Yes, that’s what my words meant. append() included and html() replace

  • 1

    pq in case the DOM is always rewritten, unless it is using a framework like the React that uses the VDOM that prevents the full reload of the gift and only overwrites object that should be overwritten, improving the performance of the page.

0

The $.html() has two functions:

1) Return the internal HTML of an element:

<div>
   <p>Parágrafo</p>         <---
   <a href="url">Link</a>       | HTML interno
   <br>                     <---  
</div>

In doing $("div").html() will return the HTML code inside the div.

2) Add HTML to an element by replacing what is:

In doing $("div").html("Olá mundo!") will replace the internal div HTML, resulting in:

<div>
   Olá mundo!
</div>

The $.append() only adds HTML at the end of the element (it does not replace what there is).

In doing $("div").append("Olá mundo!"), the result will be:

<div>
   <p>Parágrafo</p>
   <a href="url">Link</a>
   <br>
   Olá mundo!
</div>

When you use one or the other will depend on what you want to do. If you just want to add HTML to an element keeping what already exists, use the .append(). If you want to replace the widget’s HTML with another, use .html().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.