Pedro Lobito Pedro Lobito - 6 months ago 24
HTML Question

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>




Answer

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);
Comments