molu2008
molu2008

Reputation: 1257

How to convert HTMLCollection to string

I'am working on a bot that will edit some form on website, one part of the form is where is some html. I copy data from the converting to HTMLCollection do some actions, and then i want to save it back to the . And in case to do so i need to convert HTMLCollection object back to a string.

How i get and convert the data:

var htmlFromTextArea = document.getElementById('nameOfTextArea').value;
var htmlObject = document.createElement('div');
htmlObject.innerHTML = htmlFromTextArea; 
var htmlElements = htmlObject.getElementsByTagName("*")

And now i need htmlElements to become string again

I tried the following but it seems not working:

var stringWithHtmlTobeSavedInTextArea = htmlElements.text;

or

var stringWithHtmlTobeSavedInTextArea = htmlElements.textContent;

or

var stringWithHtmlTobeSavedInTextArea = htmlElements.innerText;

Upvotes: 1

Views: 4194

Answers (1)

Ritesh Khandekar
Ritesh Khandekar

Reputation: 4005

Yes, htmlElements is HTMLCollection. So seperate each element and add outerHTML of element to string using loop.

var htmlObject = document.createElement('div');
htmlObject.innerHTML = "<a>anchor</a><p>paragraph</p>"; 
var htmlElements = htmlObject.getElementsByTagName("*");
var stringWithHtmlTobeSavedInTextArea="";
for (i = 0; i < htmlElements.length ; i++){
    stringWithHtmlTobeSavedInTextArea += htmlElements[i].outerHTML;
}
console.log(stringWithHtmlTobeSavedInTextArea);

Please note that, above solution is not correctly working in case if the HTML inside div element is like <div><a>anchor</a></div>

So It is better to use innerHTML or get actual text from <textarea> eg.

var stringWithHtmlTobeSavedInTextArea = htmlObject.innerHTML;
//Or 
var stringWithHtmlTobeSavedInTextArea = htmlFromTextArea;

Upvotes: 4

Related Questions