Home > Back-end >  passing HTML with event.currenttarget to a template literal to use it as inner HTML
passing HTML with event.currenttarget to a template literal to use it as inner HTML

Time:02-24

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 >
    ${ choose}
    <div >
        <div >
            <h2>mordkaiser</h2>
            <div >
                <div >

                </div>
            </div>
            

        </div>
        <div >
            <div >

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

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

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

CodePudding user response:

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>"
  • Related