Reputation: 23
I got stuck with the following issue.
I'm explaining some content by footnotes. The footnotes e.g. [10] have the format <sup>[10]</sup>
. screenshot of content with footnotes
I'm trying to replace <sup>[10]</sup>
with <a href="#m10" data-toggle="modal"><sup>[10]</sup></a>
by using the following jQuery:
<script type='text/javascript'>
$(window).on('load', function() {
$(function(){
var s = $('sup').html().slice(1, -1);
$("sup").replaceWith('<a href="#m'+s+'" data-toggle="modal"><sup>['+s+']</sup></a>');
});
});
</script>
Unfortunately this code replaces all footnotes with the same/FIRST found footnote - in this case, all footnotes are replaced with "10" (see screenshot). I want to recursively replace each footnote.
I don't know how to solve this problem got stuck for several days. Perhaps anybody of you guys or girls can help me. Many thanks in advance.
Upvotes: 2
Views: 540
Reputation: 7032
$('sup').each(function () {
$(this).wrap('<a href="#m' + $(this).html().slice(1, -1) + '" data-toggle="modal"></a>');
});
Take a look at the .each()
method. The problem is your code only runs once, not in the context of each occurrence of <sup>
Upvotes: 2
Reputation: 28455
You need to use iterator. Try following
$('sup').each(function(){
var s = $(this).html().slice(1, -1);
$(this).wrap('<a href="#m'+s+'" data-toggle="modal"></a>');
});
Upvotes: 0
Reputation: 240928
Iterate over each of the sup
elements and replace the corresponding HTML rather than replacing all the sup
elements. Inside of the .each()
method, this
refers to the current sup
element.
Based on the jQuery you provided, you probably want:
$('sup').each(function() {
var s = this.textContent.slice(1, -1);
$(this).replaceWith('<a href="#m' + s + '" data-toggle="modal"><sup>[' + s + ']</sup></a>');
});
Rather than using .slice()
, you could also just extract the digit(s) using the .match()
method:
$('sup').each(function() {
var s = this.textContent.match(/\d+/)[0];
$(this).replaceWith('<a href="#m' + s + '" data-toggle="modal"><sup>[' + s + ']</sup></a>');
});
Upvotes: 0