简体   繁体   English

通过将href与javascript匹配来删除dom元素

[英]Remove dom elements by matching href with javascript

I need to remove some 'a tags' that have img's in them only if the a href matches exactly. 只有当a href完全匹配时,我才需要删除一些只有img的'标签'。 This is the code that needs to be removed- 这是需要删除的代码 -

<a class="slideshow" href="?Action=thumbnail&Width=500&Height=500&algorithm=proportional" rel="lightbox[eventer]" onclick="myLightbox.start(this); return false;">
    <img src="?Action=thumbnail&Width=80&Height=80&algorithm=fill_proportional">
</a>

So if the href is equal to the one above, the 'a tag' and 'img' need to be removed from the dom. 因此,如果href等于上面的那个,则需要从dom中删除'a tag'和'img'。

======edit======= ======编辑=======

I am using a proprietary CMS that spits out tags within href and src tags, I can't actually edit the code surrounding the url which makes it a bit pokey. 我使用的专有CMS在hrefsrc标签中吐出标签,我实际上无法编辑网址周围的代码,这使得它有点笨拙。

You can use code like this that will work in all browsers: 你可以使用这样的代码,它可以在所有浏览器中使用:

var links = document.getElementsByTagName("a"), item;
var urlBase = '?Action=thumbnail&Width=500&Height=500&algorithm=proportional';
var urlFull = window.location.href + urlBase;
for (var i = links.length - 1; i >= 0; i--) {
    item = links[i];
    if (item.href == urlFull || item.href == urlBase) {
        item.parentNode.removeChild(item);
    }
}

Note: the code traverses the list in reverse order so that when items are removed from the DOM and the live node list changes, it won't affect the rest of the traversal. 注意:代码以相反的顺序遍历列表,以便在从DOM中删除项目并且实时节点列表发生更改时,它不会影响其余的遍历。

Because item.href will usually return a fully qualified URL and not exactly what was in the original source HTML, we test it against both a fully qualified match and against what we were expecting in the source HTML. 因为item.href通常会返回一个完全限定的URL而不是原始源HTML中的完全限定URL,所以我们针对完全限定的匹配以及我们在源HTML中所期望的内容进行测试。

You can use querySelectorAll() and removeChild() 你可以使用querySelectorAll()removeChild()

var url = '?Action=thumbnail&Width=500&Height=500&algorithm=proportional',
    as = document.querySelectorAll('a[href="'+url+'"]'),
    i, node;

for(i=as.length;i--;){
    node = as[i];
    node.parentNode.removeChild(node);
}

support for querySelectorAll 支持querySelectorAll

I like Joseph's answer, but if you need to work with browsers that don't handle querySelectorAll() then you can use something like the following: 我喜欢Joseph的答案,但是如果您需要使用不处理querySelectorAll()浏览器,那么您可以使用以下内容:

var url = '?Action=thumbnail&Width=500&Height=500&algorithm=proportional',
    elems = document.getElementsByTagName( 'a' ),
    i = 0;
for ( ; i < elems.length; i++ ) {
    if ( elems[i].href && elems[i].href.indexOf( url ) !== -1 ) {
        elems[i].parentNode.removeChild( elems[i] );
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM