Home > Net >  How to use innerHTML safely?
How to use innerHTML safely?

Time:12-15

Instead of retyping repeated codes for a side bar in Javascript, I made a sidebar function which is used to populate similar codes for every pages. it looks like this:

function addSidebarTemplate(){
      const template = document.createElement('template');
      template.innerHTML = `<aside >
                            <header>
                <a href="."> link here</a>
                <a  href="#">
                    <i ></i>
                </a>
                <a  href="#">
                    <i ></i>
                </a>
                <a  href="#">
                    <i ></i>
                </a>
                 </header>`
       document.querySelector('#sidebar').appendChild(sidebar.content);

There are other elements below this code. But none of them requires user's input. I just wonder is this safe to use innerHTML in this case? If not, is there better way to insert the side bar like this?

Thanks

CodePudding user response:

If no user input is used, then innerHTML is fine to use. That being said, if you're doing a lot of this you may want to look into using a UI library like React to help you out.

  • Related