I have some spans inside my content, and I’d like to get the content of each of them and display it in a list.
Can anybody help me with this? Thanks.
let container = $("#article-content");
let spans = container.find(".footnote");
let outputP = $("#footnotes");
for (let span of spans) {
let listElem = document.createElement("li");
listElem.textContent = span.html;
outputP.appendChild(listElem);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
Post emensos insuperabilis expeditionis eventus <span class="footnote">footnote 1</span> asperitate nimia cuncta foedabat. propinquitate <span class="footnote">footnote 2</span> enim Excogitatum est super his<span class="footnote">footnote 3</span> adsistendo pervadendoque divites domus egentium habitu quicquid noscere poterant vel audire latenter intromissi per posticas in regiam nuntiabant, id observantes conspiratione concordi, ut fingerent quaedam et cognita duplicarent in peius, laudes vero
supprimerent Caesaris, quas invitis conpluribus formido malorum inpendentium exprimebat.
</div>
2
Answers
You could do it like this:
This will find all
span
in the element with idcontainer
, then it will append ali
element with the text of the span inside it.Demo
Use either jQuery or raw JavaScript, but not both. It’s confusing to have some native elements and some jQuery objects in a function, and sometimes it just doesn’t work. You really don’t need jQuery for something like this anyway. See https://youmightnotneedjquery.com.
The
find()
function returns only the first element that matches. Also, it’s intended to accept a filter function, not a selector string. You wantquerySelectorAll()
.There’s no element with ID
footnotes
in your markup. You need to either include it or create it with JavaScript.Bonus protip: If you use single quotes for JavaScript and double quotes for HTML (including HTML attributes inside JavaScript) you’ll rarely have the need to escape quote characters. The nice thing is that most developers use double quotes for HTML, so you’ll be consistent.