Hi,
I've written some jquery to solve this problem. Although it works, I can't help think my jquery is terrible & was hoping somebody can tell me that I'm missing something and correct my code to use something more awesome. In particular the string concat that I'm doing (commented as looking 'vomit') is lame. Can anyone unlame it?
The problem is to take the HTML below and replace the text in braces {glückliche} with the anchor from slightly further down and also replace the anchor's text with the word from in the braces. This needs to be done generically (ie not hard-coded) as there are many.
I found that inserting an anchor into text in this particular way, was not really catered for in any jquery methods - hopefully I'm wrong.
HTML given
<tr>
<td class="german">bin ich eine {glückliche} Fliege</td>
<td class="english">am I a happy fly</td>
<td>
<div class="lessonLink">
<a href="http://www.german.org/happy" title="happy">>></a>
</div>
</td>
</tr>
HTML desired
<tr>
<td class="german">bin ich eine <a href="http://www.german.org/happy" title="happy">glückliche</a> Fliege</td>
<td class="english">am I a happy fly</td>
<td>
<div class="lessonLink">
<a href="http://www.german.org/happy" title="happy">>></a>
</div>
</td>
</tr>
The jquery
$(function() {
$('td.german').each(function() {
var sentence = $(this).text();
//get the squigglied text
var startBrace = sentence.indexOf('{');
var endBrace = sentence.indexOf('}');
if (startBrace === -1 || endBrace === -1) return;
var toReplace = sentence.slice(startBrace, endBrace+1);
// find the anchor and replace it's text with squigglied
var $newAnchor = $(this).siblings().find('a').first().clone();
$newAnchor.text(toReplace.slice(1, toReplace.length-1));
//take the new anchor and insert it into the main sentence
// can I get full-string from DOM object? string concat looks vomit
var stringToInsert = '<a href="' + $newAnchor[0].href + '" ' +
'title="' + $newAnchor[0].title + '" >' +
$newAnchor[0].text + '</a>';
var newSentence = sentence.replace(toReplace, stringToInsert);
$(this).html(newSentence);
});
});