更改变量中的链接

I have variable (loaded via AJAX) that contains a piece of HTML document (but not the whole document with html, head and body.

I would like to change it this way:

For each links in this variable that points to the same domain add class internal_link.

For filtering links in the whole document I use for example:

$('a').filter(function() {
        return this.hostname && this.hostname === location.hostname;
    }).addClass('internal_link');

And it works without any problems. But I don't know how to use this code not on the whole document but on variable to change its value that way.

I tried below code:

html = data.content;

alert(html);

$(html).find('a').filter(function() {
    return this.hostname && this.hostname === location.hostname;
}).addClass('internal_link');

alert (html);

But it seems it doesn't work. internal_link class isn't in html when I run second alert.

How can it be done?

Sample page script:

<html>
<head>
    <script src="jquery-1.11.1.min.js"></script>
</head>
<body>
<script>
    $().ready(function() {

        html = '<a href="http://localhost">test</a>';

       alert(html);

        $(html).find('a').filter(function() {
            return this.hostname && this.hostname === location.hostname;
        }).addClass('internal_link');

        alert (html);


    });
</script>
</body>
</html>

Your $(html) is not an object in the html-markup. Make sure the code your looking for is a part of the markup.

Use the following setup will work:

$('html').find('a').filter(function() {
    return this.hostname && this.hostname === location.hostname;
}).addClass('internal_link');

Beside you can fire the complete function on document ready to make sure your markup is loaded:

$(document).ready(function(){
    $('html').find('a').filter(function() {
        return this.hostname && this.hostname === location.hostname;
    }).addClass('internal_link');
});

The issue is that the anchor is a root element, find() only finds children.

html = '<a href="http://localhost">test</a>';

so $(html).find('a') wouldn't work as the anchor is not a child.

You could use filter() instead, but that would only get root elements, and if you have both root elements and children if would fail,

Try it like this

var div = $('<div />').html(html); 

div.find('a').filter(function() {
    return this.hostname && this.hostname === location.hostname;
}).addClass('internal_link');

that creates a new parent element, so you're sure that any anchor in html will be a child once the content is appended to the container element.