Remove

in Javascript?

2019-07-29 11:59发布

问题:

How can i remove this <p> tag with all its content in javascript?

say i have this html code

<p class="classname">
    <input name="commit" 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?

回答1:

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



回答2:

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



回答3:

Try this:

<p id="someid">
    <input name="commit" 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();