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.