tags:

views:

302

answers:

1

Im finding jQuery to difficult to learn as there seems to be many ways to write the same thing.

As an exercise I would like to take the text within anchor tags and stuff it into the links href attribute.

eg

<a href="">http://www.something.com&lt;/a&gt;

to become

<a href="http://www.something.com"&gt;http://www.something.com&lt;/a&gt;

my first attemp was

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

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

which clearly doesnt work as I need to specify to do this action for each link.

Should I use a foreach loop? A .each() function? Or $this notation? Would they all work?

+2  A: 
$('a').text()

would return the combination of every anchor nodes text value.. I just did it on stackoverflow and it gave me:

"mederlogoutaboutfaqQuestionsTagsUsersBadgesUnansweredAsk QuestionJquery $this or each() to specify one link at a timejqueryeachthiseditcloseflagchrisadd commentjqueryeachthisask your own questionjquerythiseachC++/Unix Programmer at Waterfront International Ltdjobs.stackoverflow.comquestion feedaboutfaqblogpodcastprivacy policyadvertising infocontact usfeedback always welcomestackoverflow.comserverfault.comsuperuser.commetahowtogeek.comdoctype.comcc-wikiattribution required"

Therefore you should use jQuery.prototype.each so you can save a reference to each individual anchor's text:

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

The added benefit is that each function runs in its own execution context, each variable you define, every 'text' declared is unique to that function body so there's a lot more control inside of a .each.

Regarding the vanilla loop deal - I would use jQuery.prototype.each over it because it's a higher level function, you would have to assign a variable to the length of the nodeList and start at 0, stop at the length ( or if order doesn't matter do a reverse while loop ).. this just causes more work than necessary.

meder
thanks you makes perfect sense, any tips on how to practice jquery?
chris
Install Firebug, go to the jQuery.com website, open the console and experiment as much as you want to.
meder
just keep practising! Looking through the source will certainly help as you can see how certain commands are achieved, but I'd recommend doing that if you're familiar with JavaScript already, as some of the code can be tricky to get to a point of comprehension with
Russ Cam