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.
JavaScript
x
19
19
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<title></title>
5
<meta charset="utf-8" />
6
</head>
7
<body>
8
<textarea id="TextArea1" rows="10" cols="100"></textarea><br />
9
<textarea id="TextArea2" rows="10" cols="100"></textarea><br />
10
<input id="Submit1" onclick="parsehtml()" type="submit" value="submit" />
11
<script>
12
function parsehtml()
13
{
14
document.getElementById("TextArea2").value = document.getElementById("TextArea1").value.replace(/</?[^>]+>/ig, " ");
15
}
16
</script>
17
</body>
18
</html>
19
In my TextArea1
i have code like
JavaScript
1
11
11
1
<span>Span 1</span>
2
<select>
3
<option>opt 01</option>
4
<option>opt 02</option>
5
</select>
6
<span>Span 2</span>
7
<select>
8
<option>opt 11</option>
9
<option>opt 12</option>
10
</select>
11
This code return output like:
JavaScript
1
7
1
Span 1
2
opt 01
3
opt 02
4
Span 2
5
opt 11
6
opt 12
7
Please help me to remove all <select>...</select>
with all of it’s <option> with innerText
and want to output like this:
JavaScript
1
2
1
Span 1 Span 2
2
Thanks in advance.
Advertisement
Answer
Here updated version with different approach. We create new html element from the input value and and get span elements textContent.
JavaScript
1
10
10
1
function parsehtml()
2
{
3
let value = document.getElementById("TextArea1").value
4
let html = document.createElement('html');
5
html.innerHTML = value
6
let spans = Array.from(html.getElementsByTagName( 'span' ))
7
let result = spans.map(span => span.textContent)
8
document.getElementById("TextArea2").value = result.join(' ')
9
}
10