简体   繁体   中英

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. 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:


<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 &lt;select> element with all of its values from start tag to end tag. and want to output from dynamic generated HTML code

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 .

 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()">

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM