我需要删除具有特定src
的某些图片:
http://ukn.cs-mtc.com/wp-content/plugins/download-monitor/page-addon/thumbnail.gif
有没有办法用JavaScript删除整个<img>
标记?
答案 0 :(得分:4)
你使用jQuery吗?如果是的话,
$('img[src="http://ukn.cs-mtc.com/wp-content/plugins/download-monitor/page-addon/thumbnail.gif"]').remove();
应该有用。
...否则
var img = document.getElementsByTagName('img');
for(var i=0,i<img.length;i++) {
if(img[i].src == 'http://ukn.cs-mtc.com/wp-content/plugins/download-monitor/page-addon/thumbnail.gif') {
img[i].parentNode.removeChild(img[i]);
}
}
答案 1 :(得分:4)
我有一些空闲时间(以及写一些JavaScript的奇怪冲动......),所以我想我会提供这种功能性方法:
function removeNeighbour(el, elType) {
if (!el) {
return false;
}
else if (el.nextElementSibling) {
var nxt = el.nextElementSibling;
}
else {
var nxt = el.nextSibling;
while (nxt.nodeType !== 1 && nxt.nextSibling) {
nxt = nxt.nextSibling;
}
}
if (elType && nxt.tagName.toLowerCase() == elType.toLowerCase()) {
nxt.parentNode.removeChild(nxt);
}
else if (!elType) {
nxt.parentNode.removeChild(nxt);
}
}
function clearElsWithAttrEquals(el, attr, val, andNeighbour, neighbourType) {
if (!el || !attr || !val) {
return false;
}
else if (document.querySelectorAll) {
var matchingElems = document.querySelectorAll(el + '[' + attr + '="' + val + '"]'),
neighbourType = neighbourType || '';
for (var i = matchingElems.length - 1; i >= 0; i--) {
if (andNeighbour === true) {
removeNeighbour(matchingElems[i], neighbourType);
}
matchingElems[i].parentNode.removeChild(matchingElems[i]);
}
}
else {
var matchingElems = document.getElementsByTagName(el),
len = (matchingElems.length - 1);
for (var i = len; i >= 0; i--) {
if (matchingElems[i][attr] == val) {
matchingElems[i].parentNode.removeChild(matchingElems[i]);
}
}
}
}
clearElsWithAttrEquals('img', 'src', 'http://ukn.cs-mtc.com/wp-content/plugins/download-monitor/page-addon/thumbnail.gif', true, 'p');
快速指南(以及我可能编写的唯一文档 for )clearElsWithAttrEquals()
函数:
clearElsWithAttrEquals(el, attr, val[, andNeighbour[, neighbourType]])
;
el
:( 字符串)标识元素类型('img','p','span'...)。attr
:( 字符串)标识您要搜索的属性('id','src'等等)val
:( 字符串)只有在完全等于字符串andNeighbour
:( 布尔,可选)您是否也要移除相邻元素?通过true
(如果是)或false
(如果没有)。neighbourType
:( 字符串,可选)只有当这个元素类型('div','hr','span'时才删除邻居'等;);如果省略,那么下一个兄弟元素将被删除,无论其类型是。参考文献:
答案 2 :(得分:1)
使用jQuery:
可以轻松完成此操作$('img[src="<path>"]').remove();