skip to Main Content

Some very strange behaviour here:
What I am doing:

  1. dynamically setting class name to a td
  2. dynamically appending a div to the td

My then resulting td ends up like this:

<td class="GSCBRI<div><p>Telefon : </p></div> 17">
    <div>
        <p>Telefon : </p>
    </div>
</td>
<td class="GSCBRI 17">
    <div>
        <p>Telefon : </p>
    </div>
</td>

Naturally my code:

row.childNodes.forEach((el) => {
  el.setAttribute('class', `${row.childNodes[0].innerHTML} ${i}`);
  i++;
  let htmlDiv = document.createElement('div');
  let htmlp = document.createElement('p');
  htmlp.innerText = 'Telefon : ';
  htmlDiv.appendChild(htmlp);
  htmlDiv.setAttribute('style', 'display:none;')
  el.appendChild(htmlDiv);
})

If I comment out the el.appendChild(htmlDiv) it does not interfere with my class, but then I of course do not get the div

How is my div getting caught up in my class?

2

Answers


  1. Chosen as BEST ANSWER

    Based on T.J. Crowder's helpful observation I fixed the code like this:

    //define className outside of forEach loop
    let userName = row.childNodes[0].innerText
    row.childNodes.forEach((el) => {
    //use predefined className to append to class
      el.setAttribute('class', `${userName} ${i}`);
      i++;
      let htmlDiv = document.createElement('div');
      let htmlp = document.createElement('p');
      htmlp.innerText = 'Telefon : ';
      htmlDiv.appendChild(htmlp);
      htmlDiv.setAttribute('style', 'display:none;')
      el.appendChild(htmlDiv);
    })
    
    

  2. Instead of using .childNodes, it will be easier with using .children. It returns all of the children as HTML elements instead of the HTML nodes.

    let row = document.querySelector('tr');
    
    [...row.children].forEach((el,i) => {
      el.setAttribute('class', `${el.innerHTML} ${i}`);
      let htmlDiv = document.createElement('div');
      let htmlp = document.createElement('p');
      htmlp.innerText = 'Telefon : ';
      htmlDiv.appendChild(htmlp);
      htmlDiv.setAttribute('style', 'display:none;')
      el.appendChild(htmlDiv);
    })
    <table border="1">
      <tr>
        <td>GSCBRI</td>
        <td>GSCBRA</td>
        <td>GSCBRE</td>
        <td>GSCBRU</td>
        <td>GSCBRO</td>
      </tr>
    </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search