Mario Nezmah
Mario Nezmah

Reputation: 547

Iterate through array of paragraphs and add content from another array in JavaScript

I have 3 <p> elements which I want to change dynamically. I have values for those paragraphs in the array.

This is my HTML:

<p class="para">text xxx</p>
<p class="para">text yyy</p>
<p class="para">text zzz</p>

this is my JS:

var mobile = window.matchMedia("(max-width: 567px)")
let paragraphs = document.querySelectorAll('.para')
let paraText = [
  'text for mobile xxx',
  'text for mobile yyy',
  'text for mobile zzz'
]

if (mobile) {
  paragraphs.map(paragraph => {
    paragraph.innerText = '{belonging element from paraText}'
  })
}

How do I accomplish that?

Upvotes: 1

Views: 781

Answers (2)

FunkyDelPueblo
FunkyDelPueblo

Reputation: 167

querySelectorAll returns a NodeList not an Array, and therefore won't have the map function.

Additionally, map is used to create a new array based on an existing array, while your use case is about modifying other objects. forEach would be more appropriate here.

Instead, try either converting the NodeList into an Array :

if (mobile) {
  let paragraphsArray = [...paragraphs];
  paragraphsArray.forEach((element, i) => {
    element.innerText = paraText[i];
  })
}

or, simply iterate over paraText instead:

if (mobile) {
  paraText.forEach((text, i) => {
    paragraphs[i].innerText = text;
  })
}

Upvotes: 1

Kosh
Kosh

Reputation: 18393

Something like this?

if (window.matchMedia("(max-width: 567px)")) {
  const paraText = [
    'text for mobile xxx',
    'text for mobile yyy',
    'text for mobile zzz'
  ];

  document.querySelectorAll('.para')
    .forEach((p, i) => p.innerText = paraText[i]);
}

Upvotes: 0

Related Questions