[英]Remove selected html element from start tag to end tag with values using javascript
I'm trying to parse HTML and want to remove all <select>...</select>
from string which is from TextArea1 and want to show output (Plain Text) in TextArea2.我正在尝试解析 HTML 并希望从来自 TextArea1 的字符串中删除所有<select>...</select>
并希望在 TextArea2 中显示输出(纯文本)。 Code is given below:代码如下:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8" />
</head>
<body>
<textarea id="TextArea1" rows="10" cols="100"></textarea><br />
<textarea id="TextArea2" rows="10" cols="100"></textarea><br />
<input id="Submit1" onclick="parsehtml()" type="submit" value="submit" />
<script>
function parsehtml() {
let value = document.getElementById("TextArea1").value
.split('\n')
.filter(item => item.startsWith('<span>'))
.map(item => item.replace(/<\/?[^>]+>/ig, " ").trim()).join(' ')
document.getElementById("TextArea2").value = value
}
</script>
</body>
</html>
In my TextArea1 I have code like:在我的 TextArea1 中,我有如下代码:
<span>Span 1</span>
<select>
<option>opt 01</option>
<option>opt 02</option>
</select>
<span>Span 2</span>
<select>
<option>opt 11</option>
<option>opt 12</option>
</select>
I'm getting output like我得到的输出像
Span 1 Span 2
Code is working if I have all in a seperate line.如果我将所有内容都放在单独的行中,则代码正在运行。 But not working if I have all codes in a single line eg.但如果我在一行中包含所有代码,则不起作用,例如。
<select><option>opt 1</option></select><span>Span 1</span>...
I want to remove all <select>
element with all of its values from start tag to end tag.我想删除所有<select>
元素及其从开始标记到结束标记的所有值。 and want to output from dynamic generated HTML code并希望从动态生成的 HTML 代码中输出
Hello <select class="..." onchange="..."><option>opt 01</option><option>opt 02</option></select><span>World</span> Hello <select><option>opt 11</option><option>opt 12</option></select> <span>Again</span>
//need output like below
//Hello World Hello Again
You can create a div
, put TextArea1
's content into that div
as HTML, use Javascript's DOM support to remove select
s and copy the innerHTML
into TextArea2
.您可以创建一个div
,将TextArea1
的内容作为 HTML 放入该div
中,使用 Javascript 的 DOM 支持删除select
并将innerHTML
复制到TextArea2
。
function replaceSelect() { 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").innerText = div.innerHTML; //Copied the result into the target }
<textarea id="TextArea1"><select><option>opt 1</option></select><span>Span 1</span>...<select><option>opt 1</option></select><span>Span 2</span></textarea> <textarea id="TextArea2"></textarea> <input type="button" value="Remove Select" onclick="replaceSelect()">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.