On 2012-09-27 04:38, Gene Wirchenko wrote:
> On Thu, 27 Sep 2012 04:16:08 +0200, Stefan Weiss
>>When you write 'options.add(o)', you're not just passing the 'value' and
>>'text' properties, you're passing (a reference to) the entire object.
>
> Yes, I know. My issue is why does the second .add() wipe out the
> first when another element object is not created?
>
>>Here's a simpler but similar example:
>
> But not similar enough!
...
> o = document.createElement('option');
>
> Where is the equivalent of this last line in your code? Why do
> you not have to create a second object in your example, but not doing
> so with OP's code is why it does not work? I understand your code. I
> do not understand Christoph's.
Oh that! That's just the DOM. Remember, in justaguy's original code, he
only created a single option object and tried to add it to the select
element multiple times. That doesn't work, just like this won't work:
<div id="target"></div>
<script>
var theDiv = document.getElementById("target");
var newEle = document.createElement("hr");
theDiv.appendChild(newEle);
theDiv.appendChild(newEle);
theDiv.appendChild(newEle);
</script>
This will not append three <hr> elements to the <div>; instead it will
move the single <hr> from wherever it currently is to the end of the
<div>, three times, with the result being <div><hr></div>.
That's because we only created a single element; no matter how often we
append it or move it, it will not become two (or three) elements.
It's the same thing with the <select> and the <option> elements. The
.value and .text properties may have changed between the first and
second add(), but it was still the same element, and can only be added once.
The difference in my simpler (but apparently not so similar) example was
that you can add the same object to an array any number of times, but
not the same DOM element to a parent element.
I hope that clears it up?
> And here I thought that I understood JavaScript fairly well, but
> here we have something where it is not just that I do not understand,
> but I misunderstand.
Gene, I've been doing this (on and off) for 15 years, and I'm still not
done learning. I think what you're doing - putting these questions out
there for others to read and ponder - is the best thing you can do, for
yourself, for the group, and for people like me who can still learn
something by trying to answer in a way that keeps the pedants quiet ;)
- stefan