jQuery:如何查找每个<a> tags without link/href and replace the href with its text?

时间:2018-04-12 17:29:52

标签: javascript jquery

I have this scenario that in a page there are some <a> tags without any href links.

what I'm trying to do is to find those <a> tags and get their text and create a href attribute for them using their text.

I have tried this so far but I get this error:

Uncaught TypeError: Cannot read property 'attr' of 

My current code:

$(document.body).find("a:not([href])").contents().this.attr('href').this.attr('href').replace('htt://google.com', '');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>An unarmed man was shot in Southwest <a>Atlanta</a>, and <a href='stackoverflow.com'>Panthersville</a> residents want answers.

could someone please advice on this issue?

This is not a CSS question!!

1 个答案:

答案 0 :(得分:4)

这应该这样做:

$('a:not([href])').each(function(){
    $(this).attr('href', $(this).text())
})

&#13;
&#13;
$('a:not([href])').each(function() {
  $(this).attr('href', $(this).text())
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>An unarmed man was shot in Southwest <a>Atlanta</a>, and <a href='stackoverflow.com'>Panthersville</a> residents want answers.
<p>An unarmed man was shot in Southwest <a>Chicago</a>, and <a href='stackoverflow.com'>Panthersville</a> residents want answers.
&#13;
&#13;
&#13;

这将遍历没有href属性的所有锚点,并使用锚点文本创建属性。