Code has been added to clipboard!

Make jQuery Replace All Elements With New HTML Content

Reading time 1 min
Published Jan 23, 2018
Updated Oct 1, 2019

jQuery Replace All: Main Tips

  • The jQuery .replaceAll() inserts new HTML content instead of the specified elements.
  • This function differs from .replaceWith() (also used to make jQuery replace elements) in its syntax.

Usage of .replaceAll()

jQuery .replaceAll() replaces targeted elements with new HTML content. In the example provided you can see all <h2> elements replaced by <h1>:

Example
$("button").click(() => {
     $("<h1>Hello World!</h1>").replaceAll("h2");
});

Follow this syntax to replace jQuery elements with new content:

$(content).replaceAll(target);

The jQuery replace all elements method accepts two arguments:

  • content specifies the HTML elements to insert instead of the selected ones.
  • target defines the content to be replaced.

Note: when you remove the old nodes and replace them with new ones using jQuery replace all method, all their event handlers and data are removed as well.

Learn jQuery
Introduction
Selectors
Events
Event Methods
Download
Callback
Chaining
Get and Set
Add Element
Remove Element
Traverse
Parent
Children
Sibling Traverse
Filtering
jQuery AJAX
Effects
Show and Hide
Fade Effect
Slide Effect
Animate Effect
Manipulate CSS
Width and Height
.addClass()
.after()
.animate()
.append()
.appendTo()
.attr()
.before()
.bind() (deprecated)
.blur()
.change()
.click()
.clone()
.css()
.dblclick()
.delay()
.delegate() and .undelegate() (deprecated)
.detach()
.empty()
.end()
.error() (deprecated)
.fadeIn()
.fadeOut()
.fadeTo()
.fadeToggle()
.finish()
.focus()
.focusIn()
.focusOut()
.hasClass()
.height()
.hide()
.hover()
.html()
.innerHeight()
.innerWidth()
.insertAfter()
.insertBefore()
.keypress()
.keyup()
.live() and .die() (deprecated)
.load() (deprecated)
.mousedown()
.mouseenter()
.mouseleave()
.mousemove()
.mouseout()
.mouseover()
.mouseup()
.off()
.offset()
.offsetParent()
.on()
.one()
.outerHeight()
.outerWidth()
.position()
.prepend()
.prependTo()
.prop()
.proxy()
.queue()
.ready()
.remove()
.removeAttr()
.removeClass()
.removeProp()
.replaceAll()
.replaceWith()
.resize()
.scroll()
.scrollLeft()
.scrollTop()
.show()
.slideDown()
.slideToggle()
.slideUp()
.stop()
.submit()
.text()
.toggle()
.toggleClass()
.trigger()
.triggerHandler()
.unbind() (deprecated)
.unload() (deprecated)
.unwrap()
.val()
.width()
.wrap()
Event Properties
event.currentTarget
event.preventDefault()
event.relatedTarget
event.stopImmediatePropagation()
event.stopPropagation()
event.target
event.timeStamp
event.type
event.which
jQuery .find()
jQuery .keydown()
jQuery.noConflict()
pageY and pageX