2

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>`'

1
  • Please post your html code Commented Oct 7, 2021 at 9:44

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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>`); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.