Ryan
Ryan

Reputation: 10049

Javascript, DOM: appendChild and textContent

I submitted a Firefox addon to the mozilla directory and it was rejected because of this:

item.innerHTML =   '<table style="border-collapse: collapse; width: 100%;">'
                  + '<tr><td style="line-height: inherit; padding: 0pt; width: 100%;">'
                   + word.title
                   + '</td></tr>'
                    + '</table>';

I spoke to the editor and he tells me to "use a text node and then insert it using appendChild, textContent, etc"

That sounds like total gibberish to me, i have never used TextContent, appendChild etc and am a bit lost. Can you show me how to do the above and I'll edit the other 13 instances i have of something like the above in my script?

Thanks!

Upvotes: 1

Views: 3608

Answers (3)

scrappedcola
scrappedcola

Reputation: 10572

Rather than using innerHTML he wants you to use a function that changes the DOM in a more direct manner. AppendChild

Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node

https://developer.mozilla.org/En/DOM/Node.appendChild. The format for it is:var child = element.appendChild(child);

In your instance i would do:

var newText = document.createTextNode(word.title);
locationInDom.appendChild(newText);

Where locationInDom is where you were going to use the innerHTML. If the innerHTML was going into a table then just add an id to the specific existing column and use the method getElementById and add at that point.

Upvotes: 2

Mrchief
Mrchief

Reputation: 76258

You probably need to do something along these lines:

var t  = document.createElement("table"),
    tb = document.createElement("tbody"),
    tr = document.createElement("tr"),
    td = document.createElement("td");

    t.style.width = "100%";

    // note the reverse order of adding child        
    tr.appendChild(td);
    tb.appendChild(tr);
    t.appendChild(tb);

   // more code to populate table rows and cells
   item.appendChild(t);

Note: There are caveats to creating a table this way as things work differently between browsers. I would suggest consulting MDN to be sure about FF.

Upvotes: 5

George P
George P

Reputation: 736

He wants you to programmatically create the HTML in JavaScript. Take a read of this post, it should clear things up for you. Post a comment if you would like more information.

Upvotes: 3

Related Questions