简体   繁体   中英

Select the same new element after insertAdjacentHTML

Using native Javascript. After adding a new element via insertAdjacentHTML , I want to select that element itself ( <div id="two">two</div> ). How do I get that without having to search through the DOM?

// <div id="one">one</div>
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('beforeend', '<div id="two">two</div>');

// At this point, the new structure is:
// <div id="one">one<div id="two">two</div></div>

as per the docs

https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML

'beforeend'

Inserts the new element Just inside the element, after its last child. Hence making it the new last child.

you can use lastChild on the d1 element.

 var d1 = document.getElementById('one'); d1.insertAdjacentHTML('beforeend', '<div id="two">two</div>'); console.log(d1.lastChild) 
 <div id="one">one</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