Document.prototype.createHTML

I would like to propose an addition to the Document prototype. This is to allow you to create a new element using HTML. This is consistent with other DOM properties and methods, such as innerHTML and insertAdjacentHTML().

To illustrate the concept, I have this polyfill:

Document.prototype.createHTML=html=>{
	let template=document.createElement('template');
	template.insertAdjacentHTML('beforeend',html);
	return template.lastChild;
};

You could then use it as follows:

let img=document.createHTML('<img width="40" height="30" alt="alt text" title="title text">');
document.querySelector('h1').insertAdjacentElement('afterend',img);
img.src='https://canada1.discourse-cdn.com/free1/uploads/es/original/1X/3d70642b84aa4f28fa4ad078014b7c15a5b80cee.png';

To create the img element above using traditional DOM methods requires half a dozen steps. You wouldn’t be able to take a shortcut via insertAdjacentHTML() since that doesn’t generate a separate element which can be accessed after the event, such as when you want to change the image’s src.

In comparison, jQuery has something similar in its multipurpose jQuery() function, but this proposal adds the feature to Vanilla JavaScript.

Hi @manngo

This forum is for the JS language itself; the DOM is part of the HTML spec:
https://html.spec.whatwg.org

this is an off topic subject here at the TC39 Discourse but you can do that already with:

Range.createContextualFragment

it works for both HTML and XML
MDN link
On giving it some second thoughts, I think the DOMParser object is best for the requirements you mentioned.

let doc = new DOMParser().parseFromString('<div><b>Hello!</b></div>', 'text/html');

This article from David Walsh might be of your help!

1 Like