Pedro Lobito
Pedro Lobito

Reputation: 98901

Change a target attribute with jQuery

I'm trying to add target="_new" to every a tag after appending some content to the dom but I'm not being successful.

Please run the snippet and click "Go CORS Go", wait until the content is fully loaded and try to click on the duck. Despite being an a tag, the new attribute doesn't seem to work. Any insights ?

var url = encodeURIComponent("https://duckduckgo.com/");
$("button").click(function() {
  $.getJSON('http://anyorigin.com/get/?url=' + url + '&callback=?', function(data) {
    var cors = data.contents;
    $("body").append(cors);
    $('body a').each(function() {
      $(this).attr('target', "_blank");
    });
  });
});
<!DOCTYPE html>
<html>
<head>
  <base href="https://duckduckgo.com/" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
  <button>Go CORS Go</button>
</body>
</html>

Upvotes: 0

Views: 2347

Answers (4)

Rayon
Rayon

Reputation: 36609

Response returned by ajax had a script which is causing an error, ReferenceError: DDG is not defined(…) which will hald the execution of statements after the ReferenceError

Place your .append statement in try..catch hence error will not affect your later script.

var url = encodeURIComponent("https://duckduckgo.com/");
$("button").click(function() {
  $.getJSON('http://anyorigin.com/get/?url=' + url + '&callback=?', function(data) {
    var cors = data.contents;
    try {
      $("body").append(cors);
    } catch (Exception) {
      console.log(Exception);
    }
    $('body a').attr('target', "_blank");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button>Go CORS Go</button>

Update: As suggested in comments, .attr( attributeName, value ) sets one or more attributes for the set of matched elements so no need to iterate a elements.

Upvotes: 1

choz
choz

Reputation: 17858

I assume that all the a elements are stored in cors.

You can set their targets before appending them to body.

E.g

$("button").click(function() {
  $.getJSON('http://anyorigin.com/get/?url=' + url + '&callback=?', function(data) {
    var $cors = $(data.contents);
    $cors.find('a').attr('target', '_blank');
    $('body').append($cors);
  });
});

Upvotes: 1

Prasad Raja
Prasad Raja

Reputation: 703

Try this simple line

Old

  $("body").append(cors);
  $('body a').each(function() {
        $(this).attr('target', "_blank");
   });

Updated

 $("body").append(cors).find("a").attr('target', "_new");    

Upvotes: 0

madalinivascu
madalinivascu

Reputation: 32354

Edit the ajax result instead of the result of the page after the append

try the following:

  var newcors = $(cors).find('a').attr('target', "_blank").end();
$('body').append(newcors);

Upvotes: 1

Related Questions