简体   繁体   中英

passing HTML with event.currenttarget to a template literal to use it as inner HTML

so there is an event listener that going to give its own HTML to the function called aww with event.currenttarget in order to render it again with innerHTML, I pass it with a const called choose when I log the choose , its give the HTML correctly but when I render the page in its place this will show up: [object HTMLDivElement] so tried to use JSON.parse on it to remove string but it didn't work:

document.querySelector(".h1").addEventListener("click",aaw)
document.querySelector(".h2").addEventListener("click",aaw)
document.querySelector(".h3").addEventListener("click",aaw)
function aaw(event) {
    const choose = event.currentTarget
    document.body.innerHTML =
        `
    <div class="container">
    ${ choose}
    <div class="monster">
        <div class="monster-up">
            <h2>mordkaiser</h2>
            <div class="outside-bar">
                <div class="inside-bar">

                </div>
            </div>
            

        </div>
        <div class="monster-down">
            <div class="dicerools">

            </div>
            
        </div>
        
    </div>

    <button>attack</button>
</div>
    
    
    `
}

How can we put that e.currenttarget into the template literal to use it with innerHTML?

You're trying to interpolate a node, typeof object, with a string, which will annoyingly give you [object Object] or in your case, [object HTMLDivElement] . If you want to embed the node's HTML, you can easily access it with the innerHTML attribute:

const choose = event.currentTarget.innerHTML; // <-- Will return something like "<div>hello</div>"

And it will be rendered as HTML in your string interpolation.

Edit

If you want the HTML including its parent, simply change innerHTML to outerHTML :

const choose = event.currentTarget.outerHTML; // <-- Will return something like "<div><div id="child">blah</div>helllo<button>cool</button></div>"

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