How can i remove this <p>
tag with all its content in javascript?
say i have this html code
<p class="classname">
<input name="mit" value="Get Value" type="submit"> <span>or Cancel</span>
</p>
Now i need to replace/remove it in javascript, does anyone know how i can remove it?
How can i remove this <p>
tag with all its content in javascript?
say i have this html code
<p class="classname">
<input name="mit" value="Get Value" type="submit"> <span>or Cancel</span>
</p>
Now i need to replace/remove it in javascript, does anyone know how i can remove it?
Share Improve this question edited Apr 27, 2010 at 10:00 Marcelo Cantos 186k40 gold badges335 silver badges366 bronze badges asked Apr 27, 2010 at 9:58 streetparadestreetparade 32.9k39 gold badges105 silver badges123 bronze badges3 Answers
Reset to default 6Assuming you don't want to change the markup: The easiest way is to use a library. e.g. with jQuery:
jQuery('.classname').remove();
Otherwise, you need to get a reference to the element and then:
el.parentNode.removeChild(el);
Getting a reference to the element is the tricky part. Some browsers implement getElementsByClassName, but you'll have to write your own or use a third party implementation for the rest.
if (!document.getElementsByClassName) {
document.getElementsByClassName = function (className) {
/* ... */
}
}
If you are willing to change the markup, then give the element an id and use document.getElementById to get the reference to it.
If you have to do it in plain javascript it'll be painful because of Internet Explorer which doesn't support getElementsByClassName() (maybe in newer version ?).
var elems = document.getElementsByTagName('p');
var elemsLenght = elems.lenght;
for (var i = 0; i < elemsLenght; ++i) {
{
if (elems[i].className == 'classname')
{
elems[i].innerHTML = '';
}
}
But if you can, use a library/framework like jQuery, prototype, dojo, etc..
Try this:
<p id="someid">
<input name="mit" value="Get Value" type="submit"> <span>or Cancel</span>
</p>
function removeElement(id) {
var d = document.getElementById('myDiv');
var olddiv = document.getElementById(id);
d.removeChild(olddiv);
}
removeElement('someid');
With JQuery if you Want
$('p.classname').remove();