5

I want to take a bunch of anchor tags and make sure that they all open in a new tab.

I know I should do something like this $('a').attr('target', '_blank'); but the catch is that the HTML I am trying to modify is in a string variable.

See example:

I have a bunch of raw HTML in a string like this:

var rawHTML = 'Hello there, <a href="http://www.google.com">this</a> is a link.'

How can I convert that to be something like this:

processedHTML = 'Hello there, <a href="http://www.google.com" target="_blank">this</a> is a link.'
1
  • add string starting at a specific index Commented Aug 1, 2015 at 22:31

2 Answers 2

16

Using jQuery you can append the string to an element outside of the DOM

You can then use jQuery methods on this new element to modify the html and then return the modified string:

var rawHTML = 'Hello there, <a href="http://www.google.com">this</a> is a link.';
// create element and set string as it's content
var $div = $('<div>').html(rawHTML);
// modify attributes
$div.find('a').attr('target', '_blank');
// return modified content to string
var processedHTML = $div.html();
Sign up to request clarification or add additional context in comments.

Comments

3

In pure JavaScript, we can do this by making use of the document.createElement, Element.getElementsByTagName, and Element.setAttribute methods, as well as the Element.innerHTML getter & setter property.

Note that Element.getElementsByTagName returns an live HTMLCollection, which is why we can instantiate the links object before we insert the html string. To iterate on the collection, we invoke an array method with the collection as the this context.

This reduces some of the overhead of jQuery.

function blankify (html) {
  var root = document.createElement('span'),
      links = root.getElementsByTagName('a');
  
  root.innerHTML = html;
  
  Array.prototype.forEach.call(links, function (e) {
    e.setAttribute('target', '_blank');
  });
  
  return root.innerHTML;
}

console.log(blankify('Hello there, <a href="http://www.google.com">this</a> is a link.'));

And just because, here's a fairly flexible jQuery method. Works on the DOM, and is chainable.

jQuery.prototype.blankify = function () {
  return this.find('a').attr('target', '_blank'), this;
};

console.log($('<span/>', {
  html: 'Hello there, <a href="http://www.google.com">this</a> is a link.'
}).blankify().html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

1 Comment

I'm not sure why this answer doesn't have more upvotes, i think this should have been the accepted one because a plain JS solution is way more portable than a vendor lock-in.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.