Remove all selected HTML element with innerText using javascript

Tags: ,

I’m trying to parse html tags and want to remove <select> from code which is given in TextArea1 and want to show output in TextArea2 on button click.

<!DOCTYPE html>
    <meta charset="utf-8" />
    <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" />
        function parsehtml()
            document.getElementById("TextArea2").value = document.getElementById("TextArea1").value.replace(/</?[^>]+>/ig, " ");

In my TextArea1 i have code like

<span>Span 1</span>
<option>opt 01</option>
<option>opt 02</option>
<span>Span 2</span>
<option>opt 11</option>
<option>opt 12</option>

This code return output like:

 Span 1 
 opt 01 
 opt 02 
 Span 2 
 opt 11 
 opt 12 

Please help me to remove all <select>...</select> with all of it’s <option> with innerText and want to output like this:

Span 1 Span 2

Thanks in advance.


Here updated version with different approach. We create new html element from the input value and and get span elements textContent.

function parsehtml()
    let value = document.getElementById("TextArea1").value
    let html = document.createElement('html');
    html.innerHTML = value
    let spans = Array.from(html.getElementsByTagName( 'span' ))
    let result = => span.textContent)
    document.getElementById("TextArea2").value = result.join(' ')

Source: stackoverflow