I have a string as follows:
<div> Here is some text </div>
<div>Here is some text </div>
<ul>
<li>test 1 </li>
<li> test 2</li>
<li> test 3 </li>
</ul>
<div> Here is some text </div>
I need to loop through each element and trim the whitespace and any leading or trailing
entities using JavaScript so that the end result is as follows:
<div>Here is some text</div>
<div>Here is some text</div>
<ul>
<li>test 1</li>
<li>test 2</li>
<li>test 3</li>
</ul>
<div>Here is some text</div>
To provide more background, this is a string that is being pasted into a WYSIWYG editor. So I am simply attempting to clean up the string as it is being pasted. I'm not great with JavaScript, but even if I were to use the method suggested in the Javascript: How to loop through ALL DOM elements on a page? post, I am uncertain as to how to utilise document.getElementsByTagName("*");
in a string.
UPDATE Using @Bharata's answer, I was able to achieve the clean up using the following:
var str = "<div> Here is some text </div>" +
"<div>Here is some text </div>" +
"<ul>" +
" <li>test 1 </li>" +
" <li> test 2</li>" +
" <li> test 3 </li>" +
"</ul>" +
"<div> Here is some text </div>";
var cleanHtml = cleanUp(str);
function cleanUp(content) {
var dom = document.createElement("div");
dom.innerHTML = content;
var elems = dom.getElementsByTagName('*');
for (var i = 0; i < elems.length; i++) {
if (elems[i].innerHTML) {
elems[i].innerHTML = elems[i].innerHTML.trim();
}
}
return dom.innerHTML;
}