更新文字<a> tags in a string

时间:2015-12-08 18:58:33

标签: jquery html text

I can't make the below to return the text string with amended text for <a> tags. Can anyone suggest what am I doing wrong?

         var extra = '<a>Abcde</a><a>Bcdefg</a>'
         var extra2 = $(extra).filter('a').each(function(e){
                $(this).text('abc');
         })

Every attempt to alert(extra2) results in [object Object]. When I console.log it, I can see the amended text, but I can't just print the desired string

<a>abc</a><a>abc</a>

Please ignore the above. I found that there's no issue with it anymore after some adjustments with the rest of my code and it works. It doesn't work in a way I'd want it to though. What I'm trying to achieve is

var extra = "<a href="http://etc">Abcdefghij</a> how to make it work properly? <a href="http://etc">Defghijk</a>

var extra2 = magic(extra);

And in result I'd like to get

<a href="http://etc">abc</a> how to make it work properly? <a href="http://etc">abc</a>

I will be grateful for any hints. Thanks.

2 个答案:

答案 0 :(得分:2)

var extra = 'test<a>Abcde</a><a>Bcdefg</a>';
var $extra2 = $('<div>').append(extra);

$extra2.find('a').each(function(e){   
     $(this).text('abc')
});

所以$ extra2包含你想要的数据。 有关详细信息,请参阅文档https://api.jquery.com/each/

编辑:使用var extra2 = $extra2.html();来获得html表示(字符串)

答案 1 :(得分:0)

试试这个

$('a').text('abc');

所有<a>代码都有&#39; abc&#39;内部