'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>`'
Solution 1:[1]
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>
Solution 2:[2]
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>`);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
