Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the same new element after insertAdjacentHTML

Tags:

javascript

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>
like image 508
Victor Avatar asked Jan 03 '17 16:01

Victor


1 Answers

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>
like image 131
Deep Avatar answered Nov 08 '22 18:11

Deep