Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method to change self-closing tags to explicit tags in Javascript?

Does there exist a method or function that can convert the self-closing tags to explicit tags in Javascript? For example:

<span class="label"/>

converted to :

<span class ="label"></span>

I would like to copy a new HTML from the iframe to the outerHTML of the main page, as the new HTML generated contains self-closing tags, the outerHTML doesn't recognize them and then doesn't change and the page doesn't show correctly. But when the format is standard, that is,with the non-self-closing tags, the outerHTML will take the new HTML,and the page shows perfectly.This is why I would like to change the tags.


And this html is in a string

In fact, I don't want to parse HTML, I just want to find the "< span.../>"and replace it with "< span...>< /span>"

like image 903
Jamie Avatar asked May 16 '11 09:05

Jamie


People also ask

How do I turn off SVG tag?

A Self-closing tag is a special form of start tag with a slash immediately before the closing right angle bracket. These indicate that the element is to be closed immediately, and has no content. Where this syntax is permitted and used, the end tag must be omitted.

Which of these tags is a self closing tag?

The br tag inserts a line break (not a paragraph break). This tag has no content, so it is self closing.

Can script tags be self closing?

In the same way, there are some tags which cannot be self-closed. And <script> tag is one of them. Basically, the concept of self-closing tags is an XML concept. You can use them in XHTML if the document is served with an XML content-type but not if it is served as text/html.

What is a closing tag in Javascript?

A self-closing tag is an element of HTML code that has evolved in the language. Typically, the self-closing tag makes use of a “/” character in order to effectively close out a beginning tag enclosed in sideways carets.


2 Answers

try this to replace all self closing tags out of your string (xml/html)

function removeSelfClosingTags(xml) {
    var split = xml.split("/>");
    var newXml = "";
    for (var i = 0; i < split.length - 1;i++) {
        var edsplit = split[i].split("<");
        newXml += split[i] + "></" + edsplit[edsplit.length - 1].split(" ")[0] + ">";
    }
    return newXml + split[split.length-1];
}
like image 131
Cracker0dks Avatar answered Sep 23 '22 23:09

Cracker0dks


I'd use regex:

var spansFixed = htmlString.replace(/<span(.*)\/>/g, '<span$1></span>');

like image 24
neciu Avatar answered Sep 23 '22 23:09

neciu