Skip to content

Instantly share code, notes, and snippets.

@magopian
Created April 19, 2018 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magopian/892c3aae2f40423fdf54830ae9594a68 to your computer and use it in GitHub Desktop.
Save magopian/892c3aae2f40423fdf54830ae9594a68 to your computer and use it in GitHub Desktop.
Paste table data from copying from excel/libreoffice, and change <br /> to newlines
/* Quick and dirty experiment:
* Copy cells from a spreadsheet document (excel, libreoffice), and paste in a web page.
* Replace the <br /> in the cells with new lines, so when getting the innerHTML or the textContent,
* the result is "formatted".
*/
document.addEventListener("paste", evt => {
const content = evt.clipboardData.getData("text/html");
console.log("content:", content);
const parser = new DOMParser();
const doc = parser.parseFromString(content, "text/html");
console.log("doc:", doc);
const cells = doc.getElementsByTagName("td");
const firstCell = cells[1];
const newLine = document.createTextNode("*\n*");
const brList = firstCell.getElementsByTagName("br");
console.log("brList:", brList);
Array.from(brList).map(n => n.parentNode.replaceChild(newLine.cloneNode(true), n));
console.log("firstCell html:", firstCell.innerHTML);
console.log("firstCell text:", firstCell.textContent);
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment