Improve API of insertAdjacent*()
methods
#10122
Labels
addition/proposal
New features or enhancements
needs implementer interest
Moving the issue forward requires implementers to express interest
What problem are you trying to solve?
insertAdjacentHTML()
is fantastic for templating. It bridged an old usability cliff where authors had to either give up working with HTML strings, or do a lot of painful wrangling withinnerHTML
if they only wanted to insert an HTML fragment inside or relative to another element, rather than replace the entire contents of an element.However, due to its origins, the API is …let’s say suboptimal and clumsy.
The position arguments are excessively long and inconsistent with related DOM methods (e.g.
child.before()
but"beforebegin"
), and there’s not even a default for the first argument, so authors are forced to specify them on every call.Furthermore, we also have
insertAdjacentElement()
andinsertAdjacentText()
methods, which are simply worse APIs forbefore()
/after()
/append()
/prepend()
, presumably included for compat.How would you solve it?
Option 1: Overloading
insertAdjacent*()
methods"before"
instead of"beforebegin"
"after"
instead of"afterend"
"start"
(or"prepend"
?) instead of"afterbegin"
"end"
(or"append"
?) instead of"beforeend"
position
to"end"
Option 1b: Instead of overloading the signature with a one argument signature to default
position
, introduce a dictionary argument withposition
andhtml
keys (ortext
ornode
for the other two).Pros:
Cons:
Option 2: Introducing new
<position>HTML()
methodsThis would introduce new HTML methods like
appendHTML()
,prependHTML()
,beforeHTML()
,afterHTML()
Not a huge fan of this approach, as it increases the API surface significantly, and having different methods that do related but different things is an antipattern. However, it's the only one that doesn't involve overloading existing methods.
Option 3: Overload
element.append()
,element.prepend()
,node.before()
,node.after()
Since these already handle strings as text nodes, overloading wouldn't work. However, a dictionary overload with an
html
key still could. We probably want to be able to combine HTML strings with elements and text nodes, so this would still accept multiple arguments, each of which can be a dictionary.Pros:
insertAdjacent*
is not available there.Cons:
element.insertAdjacentHTML("before", foo)
vselement.beforeHTML(foo)
vselement.before({html: foo})
)Option 4: Single
node.insert(...content)
method to rule them allThis would basically encompass all
insertAdjacent*
PLUS functionality in a single method.content
could be either a string (which would create a text node), a node, or a dictionary with the following structure:The method would ideally be available on
Node
and would error ifstart | end
are used on non-elements.Pros:
insertAdjacent*
should have beenCons:
html
,text
,node
is specified? Do we get all of them or do we throw?The text was updated successfully, but these errors were encountered: