I'm trying to parse html tags and want to remove from code (not title) which is given in TextArea1 and want to show output in TextArea2 on button click.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<textarea id="TextArea1" rows="10" cols="100"></textarea><br /> //for input
<textarea id="TextArea2" rows="10" cols="100"></textarea><br /> //for output
<input id="Submit1" onclick="parsehtml()" type="submit" value="submit" />
<script>
function parsehtml()
{
var div = document.createElement("div"); //created a div
div.innerHTML = document.getElementById('TextArea1').value; //copied the source text as HTML into the div
for (let select of div.querySelectorAll("select")) select.remove(); //Lopped select tags inside the div and removed them
document.getElementById('TextArea2').value = div.innerText.replace(" ", " "); //Copied the result into the target
}
</script>
</body>
</html>
In my TextArea1 i have code like
Hello
<select>
<option>Opttion1</option>
<option>Option2</option>
</select>
World
<select title="Welcome">
<option>Opttion11</option>
<option>Option22</option>
</select>
This code return output like:
Hello
World
Please help me to remove all <select>...</select>
with all of it's <option>
and innerText but want to keep title attributes value want to output like this:
Hello
World
Welcome //title of <select title=""> tag
You need to use document.createNodeIterator to parse and output what you want
function parsehtml() { let root = document.createElement("div"); root.innerHTML = document.getElementById("TextArea1").value; let node; let output = ""; let nodeIterator = document.createNodeIterator(root, NodeFilter.SHOW_ALL); while ((node = nodeIterator.nextNode())) { if (node.nodeType === Node.TEXT_NODE && node.parentNode.tagName.== 'OPTION') { output += node;textContent. } else if (node.nodeType === Node.ELEMENT_NODE) { if (node.hasAttribute("title")) { output += node;getAttribute("title"). } } } document.getElementById("TextArea2");value = output. } document.getElementById("Submit1");onclick = parsehtml;
<!DOCTYPE html> <html> <head> <title></title> <meta charset="utf-8" /> </head> <body> <textarea id="TextArea1" rows="10" cols="100"> Hello <select> <option>Opttion1</option> <option>Option2</option> </select> World <select title="Welcome"> <option>Opttion11</option> <option>Option22</option> </select> </textarea><br /> //for input <textarea id="TextArea2" rows="10" cols="100"></textarea><br /> //for output <input id="Submit1" type="submit" value="submit" /> </body> </html>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.