1

I'm just starting to learn Javascript and I could use some help with this problem I'm having. I'm currently trying to add a p tag within a div tag that is in another div tag using DOM manipulation.

<div class='xxx'>
   <div> <-- I was able to create this div through DOM manipulation
      <p></p> <!-- Trying to add this tag through DOM manipulation
      <p></p> <!-- Trying to add this tag through DOM manipulation
      <p></p> <!-- Trying to add this tag through DOM manipulation
   </div>
</div>

I searched on Stackoverflow and wasn't able to find what I was looking for. So far this is what I've tried among a few other methods.

Was able to create div here:
const mainFoodDiv = document.querySelector('.food-names')
for (let i = 0; i < foodCategoryArr.length; i++) {
  const foodName = document.createElement('div')
  mainFoodDiv.append(foodName)
}

Getting an error that says foodNameP.append is not a function:
const foodNameP = document.querySelectorAll('div > div')
for (let i = 0; i < foodCategoryArr.length; i++) {
  const foodName = document.createElement('p')
  foodName.textContent = foodCategoryArr[i]
  foodNameP.append(foodName)
}

Can anyone guide me on where to go from here? I can only use pure javascript for this, no libraries or frameworks.

2
  • It would appear from your code that the second <div>...</div> tags are not needed. I see no CSS that effects them and the <p> tags would act the same without them. Commented Aug 17, 2020 at 19:40
  • 1
    I can only use pure javascript for this, no libraries or frameworks. WHY did you tag it jquery then? Commented Aug 17, 2020 at 19:55

1 Answer 1

1

foodNameP would be an array of NodeList as querySelectorAll returns that

if you are sure div > div only occur ones or is first to occur in DOM do this

foodNameP[0].append(foodName)

Or you can apply a class to it then above.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.