I've wrote this so it changes the href of the anchor with the class name but I also would like it to change the target, how do I add this?
window.onload = function() {
var change = document.getElementsByTagName('a');
for (var i = 0; i < change.length; i++) {
if (change[i].className.match('(^|\\s+)classnamegoeshere(\\s+|$)')) {
change[i].href = "/urlgoeshere";
break;
}
}
}
I've wrote this so it changes the href of the anchor with the class name but I also would like it to change the target, how do I add this?
window.onload = function() {
var change = document.getElementsByTagName('a');
for (var i = 0; i < change.length; i++) {
if (change[i].className.match('(^|\\s+)classnamegoeshere(\\s+|$)')) {
change[i].href = "/urlgoeshere";
break;
}
}
}
Share
Improve this question
asked Mar 12, 2013 at 14:42
user1975031user1975031
2611 gold badge3 silver badges9 bronze badges
4
- You should take a look at jQuery, which would make this task simple and cross browser. – Mikael Östberg Commented Mar 12, 2013 at 14:44
- 3 @MikaelÖstberg I know jQuery and could've done this in a breeze although for this situation, I didn't see the need in including jQuery for this one thing. – user1975031 Commented Mar 12, 2013 at 14:45
- Ok, your call. Maybe jQuery isn't the silver bullet one off solution to all worlds problem. I just wanted to make you aware of its existence as you appear to be a pretty new user here. – Mikael Östberg Commented Mar 12, 2013 at 14:49
- Yeah, I love jQuery, I just didn't need it in this instance. – user1975031 Commented Mar 12, 2013 at 14:53
2 Answers
Reset to default 7change[i].setAttribute('target', '_blank');
Try this
window.onload = function() {
var change = document.getElementsByTagName('a');
for (var i = 0, j =change.length; i < j ; i++) {
if ((' ' + change[i].className + ' ').indexOf(' ' + "smeCls" + ' ') > -1) {
change[i].href = "http://www.google.";
}
}
}