Ravinder Godara
Ravinder Godara

Reputation: 57

Remove HTML Elements with values using javascript

I'm trying to remove <select>....</select> html element with all of it's it's values (option) on click event. like

<span>Span First</span>
<select>
<option>opt 01</option>
<option>opt 02</option>
</select>
<span>Span Second</span>
<select>
<option>opt 11</option>
<option>opt 12</option>
</select>

Want to output like this:

Span First Span Second

I'm using code like:

<script>
function removeTags(str)
{
if ((str===null) || (str===''))
return false;
else
str = str.toString();
return str.replace( /(<([^>]+)>)/ig, '');
}
document.write(removeTags('<html> Tutorix is <script> the best <body> e-learning platform'));;
</script>

Above code working fine but unable to remove value inside <option>opt ..</option>

Can anyone help me please.

Upvotes: 0

Views: 295

Answers (2)

mathu mitha
mathu mitha

Reputation: 497

You can try DOM's removeChild() method to remove the elements. You can also use latest remove() method.

Array
 .from(parentNode.querySelectorAll('sele 
 ct').forEach((elem) => {
       parentNode.removeChild[elem]
  })

Upvotes: 0

Marc
Marc

Reputation: 11613

Remove the <select> elements with .remove().

document.querySelectorAll("select").forEach(el => el.remove());
<span>Span First</span>
<select>
<option>opt 01</option>
<option>opt 02</option>
</select>
<span>Span Second</span>
<select>
<option>opt 11</option>
<option>opt 12</option>
</select>

Upvotes: 1

Related Questions