18

I'm messing around with jQuery and ran in to a problem I can't seem to solve. I know it's possible with jQuery, but can't find a proper example to work off of. I have a page with a couple regular links with the attribute/value target="_blank" added to it.

What's the best approach with jQuery/JavaScript to remove that value from every link on the page?

1 Answer 1

46

This should do it with jQuery...

$('a[target="_blank"]').removeAttr('target');

With a modern browser...

Array.from(document.querySelectorAll('a[target="_blank"]'))
  .forEach(link => link.removeAttribute('target'));

With an older browser such as earlier IEs...

var links = document.links, i, length;

for (i = 0, length = links.length; i < length; i++) {
    links[i].target == '_blank' && links[i].removeAttribute('target');
}
6
  • 1
    Why bother with the .slice()? Since you're using .forEach(), just set the context of that method. [].forEach.call(document.querySelectorAll(...
    – user1106925
    Apr 11, 2012 at 2:17
  • 1
    @amnotiam I hadn't considered that, but it is indeed a better way to achieve it. Thanks for your comment, I've updated my answer.
    – alex
    Apr 11, 2012 at 2:20
  • Not a big fan of doing things in comparison expressions, it's clearer to me and likely others to use 2 extra characters and write : if (links[i].target == '_blank') links[i].removeAttribute('target'); or just set it to '' regardless: links[i].target = '';
    – RobG
    Apr 11, 2012 at 2:40
  • 1
    @RobG I agree it can be a little difficult to follow, at first. I thought the removeAttribute() would be cleaner than setting target to an empty string, I know it's empty even if the attribute is missing but I wasn't sure if it'd remove the attribute if I set to empty when it existed already, not that it matters as the result is the same. The set it regardless would overwrite target attributes which were not _blank.
    – alex
    Apr 11, 2012 at 2:54
  • Not in a month of Sundays would I ever have come up with version 2 - modern browser code. Arcane but neat. Apr 11, 2012 at 4:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.