JavaScript - 通过id的一部分去除元素 [英] JavaScript - removing element by part of id

查看:86
本文介绍了JavaScript - 通过id的一部分去除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要移除 id 中的< div> 元素。我知道我可以使用函数,例如 -

  function removeElement(div_id){
var div = document.getElementById (div_id);
element.parentNode.removeChild(div);
}

但事实是 id - 复合。它由一个不断变化的部分和部分组成,每个请求都有所不同。这部分是一组随机数。



我知道,在这种情况下,我需要使用正则表达式。我非常感谢一个例子。

解决方案

以下是您可以如何使用纯JavaScript而不使用任何库: p>

  var divs = document.getElementsByTagName('div'),
forEach = Array.prototype.forEach,
regex = /^foo.*$/;

forEach.call(divs,function(d){
if(d.id!== undefined&&& regex.test(d.id)){
d.parentNode.removeChild(d);
}
});

在上面的例子中,所有以 foo 开头的div元素都将被删除。
下面是一个例子: http://jsfiddle.net/UemQ5/


I need remove the <div> element on its id. I know that i can use function such as -

function removeElement(div_id) {
   var div = document.getElementById(div_id);
   element.parentNode.removeChild(div);
}

But the fact is that the id - composite. It consists of a constant part and part that change in every request. This part is a random set of numbers.

I know, i need to use regular expressions in this case. I would be most grateful for an example.

解决方案

Here is how you can do this with pure JavaScript without any libraries:

var divs = document.getElementsByTagName('div'),
    forEach = Array.prototype.forEach,
    regex = /^foo.*$/;

forEach.call(divs, function (d) {
    if (d.id !== undefined && regex.test(d.id)) {
        d.parentNode.removeChild(d);
    }
});​

In the example above all div elements which ids start with foo will be removed. Here is an example: http://jsfiddle.net/UemQ5/

这篇关于JavaScript - 通过id的一部分去除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆