Fereydoon
Fereydoon

Reputation: 81

is there a way to bind html tags to some array indices?

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

Answers (1)

hgb123
hgb123

Reputation: 14871

You could use map with index.

If indices includes index, return element wrapped around spantag, 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

Related Questions