Reputation: 81
I need to bind a span with a class to some indices of an array and print that array strings like below example:
var mainArray = ["I", "am", "not", "a", "doctor"];
var indices = [1,4]
document.getElementById("demo").innerHTML = result;
i want to get this string result :
var result = "I <span class="bg-light"> am </span > not a <span class="bg-light"> doctor </span>"
Upvotes: 1
Views: 42
Reputation: 14871
You could use map
with index.
If indices
includes index
, return element wrapped around span
tag, else return the same element
After that, join
the result with space
var mainArray = ["I", "am", "not", "a", "doctor"];
var indices = [1,4]
var result = mainArray
.map((el, index) => indices.includes(index) ? `<span class="bg-light"> ${el} </span>` : el)
.join(' ')
document.getElementById("demo").innerHTML = result;
.bg-light {
background-color: red
}
<div id="demo"></div>
Upvotes: 4