DEV Community

Cover image for I forgot about el.outerHTML so I made this
Shuvo
Shuvo

Posted on

I forgot about el.outerHTML so I made this

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.

GitHub logo 0shuvo0 / htmlToString

I forgot about el.outerHTML so I made this, it takes a DOM element and returns its html as string

htmlToString explaination meme

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>
Enter fullscreen mode Exit fullscreen mode

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))
Enter fullscreen mode Exit fullscreen mode

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.

  1. What's the tag name of the element
  2. How to get all the attributes present on a HTML element
  3. 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()
Enter fullscreen mode Exit fullscreen mode

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"'
Enter fullscreen mode Exit fullscreen mode

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")
}
Enter fullscreen mode Exit fullscreen mode

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

0shuvo0 image

Support me on Patreon

Patreon Logo

Top comments (0)