0

I'm trying to append a child to a td element. here is the HTML I am working with,

<td colspan="8" class="sectionExpandColumn courseResultLL courseResultLR">
    <a class="sectionExpand collapsibleCriteria" action=sectionDetail">
        sections
    </a>
  </td>

I want it to be,

<td colspan="8" class="sectionExpandColumn courseResultLL courseResultLR">
    <a class="sectionExpand collapsibleCriteria" action=sectionDetail">
        sections
    </a>
    <a class="sectionExpand collapsibleCriteria" action=sectionDetail">
        discussion
    </a>
  </td>

just simply addding a link tag under td, really.

so in my script,

div = table.getElementsByClassName("sectionExpandColumn");
var button = document.createElement("a");
button.setAttribute("class", "sectionExpand.collapsibleCriteria");
button.innerHTML = "Discussion";
div.appendChild(button);

I am getting Uncaught TypeError: div.appendChild is not a function Why is it?

Update

Thank you for telling me that I'm working with a htmlcollection!

So I added this code,

for (var i=0; i<div.length; i++){
    div[i].appendChild(button);
  }

But it runs through just fine, but at the end, it only adds the element to the last div. I'm trying to make a sense out of this... Could you tell me why?

Community
  • 1
  • 1
PowerLove
  • 303
  • 8
  • 25
  • 1
    Because `div` is not td, it's HTMLCollection: https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName – Teemu Aug 19 '16 at 18:27
  • 1
    **div** is an *array like object* of elements, not an element. – JonSG Aug 19 '16 at 18:29
  • 1
    Did you want the element to be appended to every td with class of sectionExpandColumn or just one in particular? – mattfetz Aug 19 '16 at 18:37
  • I want the be appended to every td. I updated my question. Could you please look at it? – PowerLove Aug 19 '16 at 19:14

3 Answers3

1

In this instance, your variable div is not an element, but an array like object. You can try:

div = table.getElementsByClassName("sectionExpandColumn");
var button = document.createElement("a");
button.setAttribute("class", "sectionExpand.collapsibleCriteria");
button.innerHTML = "Discussion";

div[0].appendChild(button);
JonSG
  • 10,542
  • 2
  • 25
  • 36
0

Try this simple code:

<td colspan="8" class="sectionExpandColumn courseResultLL courseResultLR">
        <a class="sectionExpand collapsibleCriteria" action="sectionDetail">
            sections
        </a>

      </td>

Jquery:

$('.sectionExpandColumn').append('<a class="sectionExpand collapsibleCriteria" action=sectionDetail"> discussion</a>');
Nihar Sarkar
  • 1,187
  • 1
  • 13
  • 26
0

Try This

    var div = document.getElementsByClassName("sectionExpandColumn");
    var button = document.createElement("a");
    button.setAttribute("class", "sectionExpand.collapsibleCriteria");
    button.innerHTML = "Discussion";
    div.innerHTML +=button;
Parithiban
  • 1,656
  • 11
  • 16