用JS类将multiplle元素的字符串部分替换为类

时间:2019-03-10 12:10:38

标签: javascript html

我正在学习JS,但是仍然有一些麻烦。我设法编辑了一个WYSIWYG编辑器,以允许用户单击插入以下HTML的按钮“脚注”:

<span class="footnote" data-toggle="tooltip" title="footnote">[FN]</span>

使用一些CSS,我可以在向上计数的元素内放置一个数字:

body {
    counter-reset: footnotecounter;
}
span.footnote:before {
    counter-increment: footnotecounter;
    content: counter(footnotecounter);
    position: relative;
    top: -0.4em;
    visibility: visible;
}

span.footnote {
    color: #0389b9;
    font-size: 0.875rem;
}

一些HTML示例:

Here is a text with a note.<span class="footnote" data-toggle="tooltip" title="footnote">[FN]</span> And there will be a second one too!<span class="footnote" data-toggle="tooltip" title="footnote">[FN]</span>

我实际上使用Popper和Twitter Bootstrap在工具提示中显示“脚注”的内容。

现在我要做的是,使用以下JavaScript从具有类[FN]的所有span元素中删除footnote

footnotes = document.getElementsByClassName('footnote');
for (var i = 0; i < length; i++){
  footnotes[i].replace("[FN]", " ");
}

这似乎行不通,但我不知道我的错误在哪里。而且,我想,既然我将使用JS来更改脚注,那么我不妨将CSS完全排除在外,而使用JS在所有元素中创建越来越多的内容,对吗?

这里是JSFiddle,以显示实时示例。

1 个答案:

答案 0 :(得分:1)

您必须检查脚注节点列表的 length 属性。您正在尝试替换元素本身而不是其中的文本。您必须替换元素的 textContent innerText 属性。

尝试以下方式:

var footnotes = document.getElementsByClassName('footnote');
for (var i = 0; i < footnotes.length; i++){
  footnotes[i].textContent = footnotes[i].textContent.replace("[FN]", " ");
}
body {
    counter-reset: footnotecounter;
}
span.footnote:before {
    counter-increment: footnotecounter;
    content: counter(footnotecounter);
    position: relative;
    top: -0.4em;
    visibility: visible;
}

span.footnote {
    color: #0389b9;
    font-size: 0.875rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
Here is a text with a note.<span class="footnote" data-toggle="tooltip" title="footnote">[FN]</span> And there will be a second one too!<span class="footnote" data-toggle="tooltip" title="footnote">[FN]</span>
</p>

更新:根据评论中的讨论

var footnotes = document.getElementsByClassName('footnote');
for (var i = 0; i < footnotes.length; i++){
  footnotes[i].innerHTML = footnotes[i].textContent.replace("[FN]", "<span class='new'>"+ (i+1) +"</span> ");
}
body {
  counter-reset: footnotecounter;
}

span.new{
  position: relative;
  top: -0.4em;
  visibility: visible;
}

span.footnote {
  color: #0389b9;
  font-size: 0.875rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
Here is a text with a note.<span class="footnote" data-toggle="tooltip" title="footnote">[FN]</span> And there will be a second one too!<span class="footnote" data-toggle="tooltip" title="footnote">[FN]</span>
Here's the number 3 thanks to CSS: <span class="footnote" data-toggle="tooltip" title="footnote">[FN]</span> and number 4 <span class="footnote" data-toggle="tooltip" title="footnote">[FN]</span>. All of this thanks to the CSS counter
</p>