简体   繁体   中英

Append HTML from an XHR request using vanilla javascript

If I had HTML content like this:

<div id="my1">
    <div id="1">This is div 1</div> 
    <div id="2">This is div 2</div> 
    <div id="3">This is div 3</div> 
    <div id="4">This is div 4</div> 
    <div id="5">This is div 5</div> 
</div>

How can I append an HTML string returned from an XHR request that comes in like this:

<div class="cA cB cC" data-type"a">
    <div>Success Message Here<div>
    <div class="cL">Undo</div>
</div>

So the end result is:

<div id="my1">
    <div id="1">This is div 1</div> 
    <div id="2">This is div 2</div> 
    <div id="3">This is div 3</div> 
    <div id="4">This is div 4</div> 
    <div id="5">This is div 5</div>
    <div class="cA cB cC" data-type"a">
       <div>Success Message Here<div>
       <div class="cL">Undo</div>
    </div>
</div>

The thing is, I don't want to do document.createElement(div).appendChild() since it already comes formatted with classes and data attributes.

Is there a way to simply add this HTML to where I need it?

You can append to the div's innerHTML. Assuming your content to add is stored in a variable called html :

document.getElementById('my1').innerHTML += html

First of all you have to make sure that data is safe to insert it directly to prevent XSS. Then you can use method called insertAdjacentHTML: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML You can choose place to insert your raw HTML

element.insertAdjacentHTML('beforeend', rawHtml)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM