Path: csiph.com!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Ben Bacarisse Newsgroups: comp.lang.javascript Subject: Re: Open all links in new window Date: Thu, 04 Aug 2016 11:05:21 +0100 Organization: A noiseless patient Spider Lines: 43 Message-ID: <8737mku9we.fsf@bsb.me.uk> References: <59e0b44d-8ea8-431d-ae12-e7585917f23f@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain Injection-Info: mx02.eternal-september.org; posting-host="017616aa25f81ec581c44d76d61ba2f3"; logging-data="24954"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX185cjVkcO8gUfbQ0wP7MvmA2ReU7+PrguU=" Cancel-Lock: sha1:G6+o4lA47IyFqVlwEyddKGQrS3M= sha1:pdyVKBzNj0NnaPq4cJI6GnfeEA8= X-BSB-Auth: 1.93da985bd607b25db4de.20160804110521BST.8737mku9we.fsf@bsb.me.uk Xref: csiph.com comp.lang.javascript:31055 Chandramohan Akkoni writes: > On Wednesday, July 27, 2016 at 2:15:10 PM UTC+5:30, Chandramohan Akkoni wrote: >> Dear Friends, >> >> I have a website www.xyzabc.com (dummy site mentioned) and on the >> tutorials web page I have 100+ urls. Few assets are linked to my >> site and few are 3rd party links. I need a script which excludes my >> links and all 3rd party links are opened in a new tab even if I do >> not add target="_blank" or onclick().The Code should not be applied >> manually on all links, it should be one simple code. >> >> Thanks in advance. >> >> Thanks, >> Chandramohan > > I have the below code which work for small caps .pdf but does not work for .PDF and also I'm unable to check for .doc, .docx, etc. > > ---------------------------------------------------------------- > var pdfAnchors = document.querySelectorAll("a[href$='.pdf']"); > for(var i = 0; i < pdfAnchors.length; i++) { > pdfAnchors[i].target = pdfAnchors[i].target || "_blank"; > } > > ---------------------------------------------------------------- > Could you please check and get me the solution. The most flexible solution is to go back to the regular expression example (i.e. not using document.querySelectorAll) and change the match to include all the links you care about. You can match them all in one expression something like /^http|\.(pdf|doc|docx)$/i (untested). But if you can rely on up-to-date browser support, you can use case insensitive CSS attribute matching introduced in CSS4: a[href$='.pdf' i] which you'd combine with either having multiple (comma separated) selectors in querySelectorAll, or making multiple calls to the function. -- Ben.