2

I am new to JavaScript and I am trying to build a client-side reference extractor for scientific PDFs. I want each reference on a separate line. I have tried '\n' and '<br>', they do not work. Here is an example:

references = ["1", "2", "3"];
document.getElementById("output").textContent = references.join('<br>');
<div id="output">
  <div>Extracting...</div>
</div>

My output is

1<br>2<br>3

showdev
  • 28,454
  • 37
  • 55
  • 73
user572780
  • 257
  • 3
  • 10

3 Answers3

4

You should use innerHTML instead of textContent with <br />.
With textContent, the "value is not parsed as HTML"; see Differences from innerHTML.

references = ["1", "2", "3"];
document.getElementById("output").innerHTML = references.join('<br>');
<div id="output">
  <div>Extracting...</div>
</div>

You can also use innerText but then you have to use \n line separator instead of <br />

references = ["1", "2", "3"];
document.getElementById("output").innerText = references.join('\n');
<div id="output">
  <div>Extracting...</div>
</div>
showdev
  • 28,454
  • 37
  • 55
  • 73
1

You can use map to iterate through each element in the array like this:

references = ["1", "2", "3"];
references.map((reference) => {
  const node = document.createElement('p');
  const textnode = document.createTextNode(reference);
  node.append(textnode);
  document.getElementById("output").appendChild(node);
})
<div id="output">
  <div>Extracting...</div>
</div>
showdev
  • 28,454
  • 37
  • 55
  • 73
Carlos G
  • 479
  • 1
  • 8
  • 19
1

If you want each item in 'references' to be it's own HTML element, you can try looping over the array, creating a new element, and attaching it to the DOM.

for( const ref of references){
        let newEl = document.createElement('div');
        newEl.innerHTML = ref;
        document.body.appendChild(newEl);
  }
Chris L
  • 129
  • 5
  • Please consider `document.body.appendChild(newEl)`. See: [couldn't append a child node to the document](https://stackoverflow.com/questions/47662168/why-i-couldnt-append-a-child-node-to-the-document-object-model-directly). – showdev Mar 04 '20 at 21:34