How can i close all the open tags before doing insertHTML
<p>I want to insert some HTML into the Div tag after closing all the tags at cursor location.</p>

<pre><code>        var closetag = "";
        var opentag = "";
        var sel = window.getSelection();
        if (typeof window.getSelection != "undefined") {
            var Node = sel.focusNode.parentNode;
            while (Node.id != "rteName") {
                var str = Node.nodeName;
                str = str.toLowerCase();
                closetag = closetag + "&lt;/" + str + "&gt;";
                var OuterHTML = Node.outerHTML;
                var val = OuterHTML.search(str);
                if(val != -1) {
                    var Tlen = val+30;
                    var str = OuterHTML.substring(val,Tlen);
                    var len = str.search("&gt;");
                    str = OuterHTML.substring(val,val+len);
                }               
                opentag = opentag + "&lt;" + str + "&gt;";        
                Node = Node.parentNode;
            }
        }
        html = closetag + html + opentag;
        document.execCommand('insertHTML', false, html);
</code></pre>

<p>Other than mentioned above, is there any way to attain this</p>
