Is it possible to use javascript to add target="_blank" to all links that include the following in the URL: profile.php?id=
3 Answers
The following should work:
var aElems = document.links;
for (var i=0,len = aElems.length; i<len; i++){
if (aElems[i].href.indexOf('profile.php?id=') != -1){
aElems[i].target = '_blank';
}
}
Edited to improve the performance of the above code, removing document.links and replacing it with document.getElementsByTagName('a'):
var aElems = document.getElementsByTagName('a');
for (var i=0,len = aElems.length; i<len; i++){
if (aElems[i].href.indexOf('profile.php?id=') != -1){
aElems[i].target = '_blank';
}
}
It's worth noting, though, that using Chris Fulstow's querySelectorAll()-enabled $('a[href*="profile.php?id="]') approach is marginally faster (in Chromium 14/Ubuntu 11.04): JS Perf speed-test. Therefore, the following is the fastest (in browsers that support querySelectorAll()):
var aElems = document.querySelectorAll('a[href*="profile.php?id="]');
for (var i=0,len = aElems.length; i<len; i++){
if (aElems[i].href.indexOf('profile.php?id=') != -1){
aElems[i].target = '_blank';
}
}
Above assertion 'fastest' supported by JS Perf comparison, at least in Chromium 14/Ubuntu 11.04. Bear in mind, of course, that IE < 8, and Firefox 3, aren't going to play well with this approach.
Of course, the above should be corrected to:
var aElems = document.querySelectorAll('a[href*="profile.php?id="]');
for (var i=0,len = aElems.length; i<len; i++){
aElems[i].target = '_blank';
}
This is because the if condition was already evaluated by querySelectorAll(), which makes the if entirely redundant.
Modified JS Perf comparison: http://jsperf.com/anchor-selector-test/3.
3 Comments
Use JQuery or look at their source and port their logic into your own code base:
$(function(){
$('a').each(function(){
var $this = $(this);
if ($this.attr('href').indexOf('profile.php?id=') !== -1) {
$this.attr('target','_blank');
}
});
});
11 Comments
$('a[href*="profile.php?id="]').prop('target','_blank'); And if OP doesn't know how to do this simple task, looking at jQuery's source won't be much help.$('a[href*="profile.php?id="]') is a valid qSA selector, so Sizzle wouldn't be used in most browsers. And in non-qSA browsers, Sizzle will use gEBTN, then will do the filter you're doing, avoiding the need to create a new jQuery object for each <a> element. And if you were going for performance, you would have done $(document.links). And since we're in JavaScript, we should really be dealing with properties instead of attributes. So yep, I'd say I did a pretty good job.