开发者

Remove <p class="classname"> in Javascript?

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?


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.


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="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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜