Insert an element in the DOM instead of adding with dart: html

The base Element object in dart: html has an elements property, which is an implementation of List<E> . The add method adds elements to the DOM. I would like to add or insert an element in the DOM. None of the insertion methods in the ElementList are implemented. How can i do this?

+4
source share
2 answers

So let's say you have this HTML snippet:

 <body> <div id='test'></div> </body> 

You can do this to insert an element before the div:

 // Get the sibling that we want to insert before. final el = query('#test'); // From the parent element, we call insertBefore, referencing the // sibling that we want to insert the new element before. document.body.insertBefore(new Element.tag('p'), el); 

Now your HTML will be:

 <body> <p></p> <div id='test'></div> </body> 
+5
source

In addition to John Answer. You can also use the syntax:

 final el = query('#test'); // If you want an element el.insertAdjacentElement('beforebegin', new Element.tag('p')); // If you want to insert HTML tags el.insertAdjacentHTML('beforebegin', '<p>Hello</p>'); // Insert just text el.insertAdjacentText('beforebegin', 'Hello there'); 

You can use positional arguments: beforebegin, afterbegin, preend, afterend, which will place it before the beginning of another element, only inside the beginning of the element, only inside the end of the element or only outside the element, respectively.

+5
source

Source: https://habr.com/ru/post/1435788/


All Articles