75

I used the following jQuery example which works like a charm. However it appends the results. What do I need to change to replace the results instead of appending?

shaiss
  • 2,000
  • 5
  • 22
  • 33

4 Answers4

156

you could empty the element before you append

$("#results").empty().append(myHtml);

or use the html method

$("#results").html(myHtml)
Marek Karbarz
  • 28,956
  • 6
  • 53
  • 73
27

Just change

$('#results').append(myHtml);

to

$('#results').html(myHtml);
Greg
  • 316,276
  • 54
  • 369
  • 333
5

OK, last entry 2009, but if the problem still exist:

let oldElement = $('#results')
let content = '<div id="#results>9000+</div>'
oldElement = oldElement.replaceWith(content)
let newElement = $('#results')
Kevin
  • 2,234
  • 2
  • 21
  • 26
  • 2
    Usefull but it does not do the same thing tho, it replace the element instead of inserting content. – Joseph Garrone Jan 12 '18 at 18:18
  • yes, the better way to replace it's content is to use the html method –  Feb 11 '21 at 12:03
  • The question does not say which type of replacement is needed. `.text()` and `.html()` are for getting and setting the inner content of an element. `.replaceWith()` replaces the element itself. `.empty().append()` together is a convoluted way of doing `.html()`, but might be useful if there is some separation of the statements. Like if new content always gets appended, but only sometimes empties the element first. `.appendTo()` and `.replaceAll()` reverse content and elements (e.g. `$('
    ').appendTo('body')`). I think `replaceWith()` pairs well with server communications of sections by ID.
    – Kevin Jun 29 '22 at 13:01
0

Empty function before your append or prepend function.

I tried this & it worked --->

frame is id selector & it append image.

$("#frame").empty().append('<img src="" >' ); 
Tasos K.
  • 7,979
  • 7
  • 39
  • 63