The base Element
object in dart:html has a property elements
which is an implementation of List<E>
. The add
method appends elements to the DOM. I would like to prepend or insert an element into the DOM. None of the insert methods in ElementList
are implemented. How can I do this?
To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.
AppendChild. The simplest, most well-known method of appending an element to the DOM is certainly the appendChild() .
insertAdjacentHTML. insertAdjacentHTML is is like append in that it's also capable of adding stuff to DOM elements. One difference, though, is that insertAdjacentHTML inserts that stuff at a specific position relative to the matched element.
In the HTML DOM, the Element object represents an HTML element, like P, DIV, A, TABLE, or any other HTML element.
So lets 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With