javascript - Changing links in variable -
i have variable (loaded via ajax) contains piece of html document (but not whole document html, head , body.
i change way:
for each links in variable points same domain add class internal_link.
for filtering links in whole document use example:
$('a').filter(function() { return this.hostname && this.hostname === location.hostname; }).addclass('internal_link');
and works without problems. don't know how use code not on whole document on variable change value 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 seems doesn't work. internal_link class isn't in html when run second alert.
how can 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>
the issue anchor root element, find()
finds children.
html = '<a href="http://localhost">test</a>';
so $(html).find('a')
wouldn't work anchor not child.
you use filter()
instead, only root elements, , if have both root elements , children if fail,
try this
var div = $('<div />').html(html); div.find('a').filter(function() { return this.hostname && this.hostname === location.hostname; }).addclass('internal_link');
that creates new parent element, you're sure anchor in html
child once content appended container element.
Comments
Post a Comment