简体   繁体   中英

How to use querySelector to find all external links with a specific class

I want to find out all external links (links that are not pointing to the current domain) within a specific class (.post-inner) but I cannot find out how to do it. I think it could be achieved with querySelector (I am not using jQuery). This is the current code which doesn't work:

function linkopener(a) {
var c = document.links;
for (var i = 0; i < c.length; i++) {
    if (c[i].hostname != window.location.hostname && c[i].protocol != 'tel:' && c[i].protocol != 'mailto:' && c[i].querySelector('.post-inner')) {
        c[i].target = '_blank';
        c[i].rel = 'noopener noreferrer';
        c[i].title = '\u00f6ffnet in neuem Fenster - ' + c[i].title;
        c[i].className += ' external-link'
     }
}

};

If your internal links are relative (do not start with " http://yourdomain.com/ ...") You can use the querySelector to find all tags that have a protocol specifier like this:

var aTags = document.body.querySelectorAll('.post-inner a[href*="://"]');

If the tag has a "href" attribute that contains "://" and is inside an element with class "post-inner" it will be found.

Try to use

c[i].classList.contains('post-inner')

instead

我认为你可以做这样的事情,

$(".post-inner>a[href^="http:"] ,.post-inner>a[href^="tel:"], ...")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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