-1

I'm trying to add some elements to the DOM, but the FireBug console keep alerting me for an error saying TypeError: el.appendChild is not a function; el.appendChild(para); So here is the js:

var para = document.createElement("tr");
var node = document.createTextNode(data.filename);
para.appendChild(node);
var el = document.getElementsByClassName("toBeSelected");              
el.appendChild(para);

Found some common problems but couldn't find a way to solve mine.

Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
Alex
  • 485
  • 6
  • 18

1 Answers1

4
document.getElementsByClassName
                   ^

returns a collection of elements. You need to select an element from the collection before you can append a child to it.

If you know there's exactly one, you could use:

var el = document.getElementsByClassName("toBeSelected")[0];

As it's unclear whether you expect to add nodes to all of the elements with the given class, so I will explicitly assume that is what you expect to do.

elems = document.getElementsByClassName('toBeSelected');
for (i = 0; i < elems.length; i++) {
  elem = elems[i];
  tr = document.createElement('tr');
  tr.textContent = data.filename;
  elem.appendChild(tr);
}

This form is quite verbose. If you're using jQuery, then it's much simpler to write:

$('<tr>').text(data.filename).appendTo('.toBeSelected');
zzzzBov
  • 174,988
  • 54
  • 320
  • 367
  • Yeah, tried `el[0].appendChild(para);` and worked – Alex Mar 05 '16 at 18:49
  • If I want to add a `class` to the created `tr` tag, how would this be achieved – Alex Mar 05 '16 at 18:56
  • @Alex, there are numerous resources for learning JavaScript basics online. The first and foremost is Google, but MDN and StackOverflow both are good resources for learning syntax and APIs. Please exert a bit of effort in solving your own problems before asking for help. – zzzzBov Mar 05 '16 at 19:15