'Replace self closing div with proper div closing
I have a HTML string like below,
Code
<div class="col-md-1" style="margin-right:-20px" />
<div style="cursor: pointer; padding: 0px 3px; float: left;" class="Fav aLogin" title="Bookmark" />
The above html prepared by XSLT transform and I am trying to add the above html into existing div element dynamically. The problem here's when it rendered then the closing div is recognized. I found that self closing is NOT valid for div element and it should be proper closing .
I tried changing the xml output to the following but still the self closing tag is appearing.
Code
<xsl:output method="html" indent="yes" />
<xsl:output method="xhtml" indent="yes" />
So, I need a way to replace the tags which is self closing first in the HTML string then add it to the DOM. Please help to suggest.
NOTE: I hv found some ways to add some dummy elements/text within the self closing div but it is NOT feasible in my case as i have so many XSLT which has self closing tags in it.
Solution 1:[1]
If the list has markup for a self-closing div on each line without intended display text, I'd pre-process a copy of the list to replace /> with ></div>;
Solution 1, Pre-process using javascript
My snippet example splits the list into an array, each element being markup for one self-closing div. The array.map method is then used to create a new array where each element has had the string replacement made:
const list = `<div class="col-md-1" style="margin-right:-20px" />
<div style="cursor: pointer; padding: 0px 3px; float: left;" class="Fav aLogin" title="Bookmark" />
<div class="col-md-1" style="margin-right:-20px" />
<div style="cursor: pointer; padding: 0px 3px; float: left;" class="Fav aLogin" title="Bookmark" />`;
divArray = list.split('\n');
const newDivs = divArray.map(x => x.replace(" />", "></div>"));
document.getElementById('output').innerText = newDivs.join("\n");
#output {
white-space:pre;
}
<div id="output"></div>
Solution 2: preprocess using sed on command line
If you save a file containing the list of self closing div markup as (e.g) selfClose.txt, you can make the required substitutions on the command line, saving the new list to (e.g) output.txt using the stream editor sed on the command line:
sed 's/ \/\>/\>\<\/div\>/g' selfClose.txt > output.file
Note the /, >, and < characters all have to be escaped in the regular expression used for the replacement.
The generic format would be:
sed 's/old-text/new-text/g' oldFile > newFile
The s flag is for substitute, and the g flag is for global - replacing all occurrences.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
