Jquery $ this or each () to specify one link at a time

I find jQuery difficult to learn because there seem to be many ways to write the same thing.

As an exercise, I would like to take the text in the anchor tags and fill it with the href link attribute.

eg,

<a href="">http://www.something.com</a>

to become

<a href="http://www.something.com">http://www.something.com</a>  

my first attemp was

<script type="text/javascript">
$(document).ready(function() {
var text = $('a').text();

$('a').attr( 'href', text );
});
</script>

which clearly does not work, since I need to specify for this action for each link.

Should I use a foreach loop? Function .each ()? Or is $ this designation? Will they all work?

+3
source share
1 answer
$('a').text()

will return a combination of each text value of anchor nodes. I just did it on stackoverflow and gave me:

"mederlogoutaboutfaqQuestionsTagsUsersBadgesUnansweredAsk QuestionJquery $this each() to timejqueryeachthiseditcloseflagchrisadd commentjqueryeachthisask questionjquerythiseach++/Unix Waterfront International Ltdjobs.stackoverflow.comquestion feedaboutfaqblogpodcastprivacy usfeedback welcomestackoverflow.comserverfault.comsuperuser.commetahowtogeek.comdoctype.comcc-wikiattribution "

jQuery.prototype.each, :

$('a').each(function() {
    var text = $(this).text();
    $(this).attr('href', text );
});

, , , , "" , .each .

- jQuery.prototype.each , , nodeList 0, ( , while).. , .

+7

Source: https://habr.com/ru/post/1719431/


All Articles