Zain
Zain

Reputation: 33

How to inject html tags within a script in Javascript?

I have a string where I would like to inject a <br> tag based on array values.

My html code:

'Hello people. `<span>`Hello to everyone`</span>`'; 
<script>
    let array = ['Hello', 'to everyone'];
</script>

I need to inject <br> tag between 'Hello' and 'to everyone' inside <span> based on contents of array. How can I do it without replacing the tags and not affecting the first 'Hello' word?

Expected output:

'Hello people. `<span>`Hello `<br>` to everyone`</span>`'

Upvotes: 2

Views: 1056

Answers (2)

TERMINATOR
TERMINATOR

Reputation: 1248

You should do this by clearing the contents of the <span> element, then iterate over the array with a foreach method where you add the contents of the array then a line break(<br>).You can define the line break with const lineBreak = document.createElement('br'); , then you can add it to the span element with some DOM manipulation like this elem.appendChild(lineBreak)

Here is the full code:

<head>
  <title>hello world</title>

</head>
<body>
  <p>Hello people. <span id='message'  style="WHITE-SPACE: br">Hello to everyone</span></p>
  <script>
    function split_words(){
      let array = ['Hello', 'to everyone'];
      const elem = document.getElementById('message');
      let result = '';
      const lineBreak = document.createElement('br');
      elem.innerHTML = '';
      array.forEach(word => {
        elem.innerHTML += word;
        elem.appendChild(lineBreak)
        
      });
    }
    window.onload = split_words(); 
  </script>
</body>

Upvotes: 2

isofttechn
isofttechn

Reputation: 502

You could just use \n or <br/> within the text. Your code will look something like so

document.write(`Hello people. <span>Hello <br> to everyone</span>`); 

Upvotes: 0

Related Questions