jkriddle
jkriddle

Reputation: 708

Manipulating reference to DOM element using JavaScript

A project I'm working on has to manipulate DOM elements using JavaScript. When a particular event fires, I'm looping through the DOM and basically creating an index of all of the nodes in order to manipulate them later. There is more to the reason why I'm creating this index, but for simplicity sake I'm dumbing it down here.

However the problem is that when we go to manipulate the element in the DOM, it seemingly manipulates a separate object than the actual object in the DOM. Here is about as basic of an example as I could come up with:

<div id="container">
    <div>Here is some text</div>
    <div>And here is some more text</div>
</div>

<script>
    var container = document.getElementById('container');
    container.firstChild.innerHTML = 'Foobar';
</script>

Fiddle: http://jsfiddle.net/4Nngh/

But the first div is never changed to "Foobar". I'm guessing when I get the "container" element I am actually getting a separate object instead of a reference to the DOM element.

Is it possible to simply reference the element displayed in the DOM and manipulate it directly, or do I have to use some type of replacement method? Other events may change the contents of that DOM element while the script runs, so I'm trying to avoid having to re-create this index every single time the event fires, which is why I'm looking for a "reference" to the element somehow.

Thanks!

Upvotes: 0

Views: 175

Answers (1)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

The firstChild is actually the text node containing the newline-tab combo.

To get the first element child, use children[0]. The children[] array only includes element nodes.

Upvotes: 4

Related Questions