This morning I needed to convert a DOM element into a sting. And at the time I forgot about the el.outerHTML
method. And I know the el.innerHTML
will not include in element itself. It will only give inner HTML. So after doing a quick Google I was remined about the outerHTML
method. And my issue was solved!
But this got me thinking how could I do it if there was no innerHTML
or outerHTML
method.
And thus htmlToString was born.
0shuvo0 / htmlToString
I forgot about el.outerHTML so I made this, it takes a DOM element and returns its html as string
htmlToString
Convert html/DOM element to string
Works with rendered and virtual DOM
Installation
npm install htmltostring
Or using CDN
<script src="https://cdn.jsdelivr.net/npm/htmltostring@1.0.6/htmlToString.min.js"></script>
Usage
//you don't have to import if you're using CDN
import htmlToString from 'htmltostring'
console.log(htmlToString('.container'))
// or
// const container = document.querySelector('.container')
// console.log(htmlToString(container))
Example Output
<div class="container">
<h1>Hello World</h1>
</div>
And it was very simple to do using recursion.
There was just three main question.
- What's the tag name of the element
- How to get all the attributes present on a HTML element
- Check if a tag is self closing tag or not
And here are the answers
What's the tag name of the element
You can easily get the tag name of the element like this
let tagName = el.tagName.toLowerCase()
How to get all the attributes present on a HTML element
el.attributes
returns a list of attribute present on the element.
[...el.attributes].map(e => `${e.name}="${e.value}"`).join(" ")
//example outcome
//'class="main" type="text"'
Check if a tag is self closing tag or not
First we can create an array or self closing tags and then check if tag name is present in the array
const selfClosingTags = ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']
if(selfClosingTags.includes(tagName)){
console.log("Self closing tag")
}
And with all the questions answered the function was very easy to implement.
You can see the full code here
Found it useless, I mean helpful? By me a Coffee ☕
Make sure you checkout my other articles and YouTube channel
Top comments (0)