I'm trying to change the "value" on each item from an array but every time this error happen "Cannot set property 'innerHTML' of undefined "

Joeliton MDS :

I'm trying to change the values on the created elements and to make the work simpler I gave classes to them so could easily change their content later as an array but when I try doesn't work at all

    let div_section = document.createElement('div');
    for (i = 0; i < 2; i++) {
        let section_boxes = document.createElement('section');
        section_boxes +1;
        section_boxes.setAttribute('class','box');
        div_section.appendChild(section_boxes);
    
        let boxes_h2 = document.createElement('h2');
        boxes_h2 +1;
        boxes_h2.setAttribute('class','boxesTitle');
        section_boxes.appendChild(boxes_h2);

        let boxes_p = document.createElement('p');
        boxes_p +1;
        boxes_p.setAttribute('class','boxesP');
        section_boxes.appendChild(boxes_p); 

        
    };

    //Grabing classes
    let getBoxes = document.getElementsByClassName('box');
    let getTitle = document.getElementsByClassName('boxesTitle');
    let getText = document.getElementsByClassName('boxesP');
    

    //Don't know why doesn't work 
    getText[0].innerHTML = "Some Random text";
    getTitle[0].innerHTML = "Title";
    for(i = 0; i < getBoxes.length; i++){
        getBoxes[i].style.backgroundColor = "#947062";
    };

German Ochea :

you forgot to append the body thats why

  let div_section = document.createElement("div");

  for (i = 0; i < 2; i++) {
    let section_boxes = document.createElement("section");
    section_boxes + 1;
    section_boxes.setAttribute("class", "box");
    div_section.appendChild(section_boxes);

    let boxes_h2 = document.createElement("h2");
    boxes_h2 + 1;
    boxes_h2.setAttribute("class", "boxesTitle");
    section_boxes.appendChild(boxes_h2);

    let boxes_p = document.createElement("p");
    boxes_p + 1;
    boxes_p.setAttribute("class", "boxesP");
    section_boxes.appendChild(boxes_p);
  }

  // addedline of code added
  document.body.append(div_section);

  //Grabing classes
  let getBoxes = document.getElementsByClassName("box");
  let getTitle = document.getElementsByClassName("boxesTitle");
  let getText = document.getElementsByClassName("boxesP");

  //Don't know why doesn't work
  getText[0].innerHTML = "Some Random text";
  getTitle[0].innerHTML = "Title";
  for (i = 0; i < getBoxes.length; i++) {
    getBoxes[i].style.backgroundColor = "#947062";
  }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=28302&siteId=1