簡體   English   中英

使用javascript從開始標記到結束標記中刪除選定的html元素,並帶有值

[英]Remove selected html element from start tag to end tag with values using javascript

我正在嘗試解析 HTML 並希望從來自 TextArea1 的字符串中刪除所有<select>...</select>並希望在 TextArea2 中顯示輸出(純文本)。 代碼如下:

<!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>

在我的 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>

我得到的輸出像

Span 1 Span 2

如果我將所有內容都放在單獨的行中,則代碼正在運行。 但如果我在一行中包含所有代碼,則不起作用,例如。

<select><option>opt 1</option></select><span>Span 1</span>...

我想刪除所有&lt;select>元素及其從開始標記到結束標記的所有值。 並希望從動態生成的 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

您可以創建一個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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM