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?
Asked
Active
Viewed 9.2k times
4 Answers
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
-
It should be noted that `append` supports elements and an array of elements, whereas `html` does not. – vallentin Nov 02 '18 at 13:52
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
-
2Usefull 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
-
-
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

Namesh Silva
- 1
- 1