Reputation: 85
I have this in this var: "ver" Here i have few lines like this one:
<div class="link" id="1"><a ...>Anchor</a></div>
<div class="link" id="2"><a ...>Anchor 2</a></div>
I search a code in jquery that turn the above code into:
<div class="link" id="1"><a ...><img src="...?anchor=Anchor" /></a></div>
<div class="link" id="1"><a ...><img src="...?anchor=Anchor 2" /></a></div>
What i expect from the code: Find each Anchor - Get it - Generate an image that display this anchor. PS: I have the function for "Image Generating".
SOLVED:
$(".link").each(function(){
anchor = $(this).find('a').text();
$(this).find('a').html('<img src="generateLink.php?nr='+encodeURIComponent(anchor)+'" width="39" height="12"/>');
});
Upvotes: 0
Views: 2128
Reputation: 402
I guess the best way to do so is by using a regular expression.
jQuery('.link').each(function() {
jQuery(this).html(
jQuery(this).html().replace(/<a(.*)>(.*)<\/a>/g,
'<a $1><img src="..?anchor=$2" /></a>')
);
});
On the first line you tell jQuery to get each element with the class 'link'. Then you go and find each link inside that element by using '/(.*)</a>/g'.
The first group (a group looks like this: '(.*)') represents the first group we want to capture, because we'll need the information that element is carrying with it.
The second group is the information we want to store so we know what variable to give our image url.
At the fourth line we'll go and replace what we need. Each $-sign followed by a number is a group we've captured on the third line.
If you want to do some testing on regular expressions I can surely recommend http://gskinner.com/RegExr/
Upvotes: 2
Reputation: 1209
If I understood, you must change the line with:
$(this).find(a).text().replaceWith(anchor);
For
$(this).find(a).text(varwithnewcontent);
If not, sorry for it!
Upvotes: 0