I have an html element with an id of "foo":
<p id="foo"> this is a paragraph of text </p>
So in javascript, I'd like to modify it. I can do this:
document.getElementById("foo").innerHTML = "new text";
This works. It changes the text in the element with the id "foo"
to be "new text"
.
Ok, now I'd like to use javascript to add an element before the "foo" paragraph element. I looked up a resource that told me I could do something like this:
var newP = document.createElement("p");
var line = document.createTextNode("new text");
newP.appendChild(line);
var currentP = document.getElementById(foo);
document.body.insertBefore(newP, currentP);
Here's what confuses and surprises me. On the 4th line, var currentP = document.getElementById(foo);
no quotes are used. In fact, if I add quotes, it doesn't work.
Why does the first example of document.getElementById()
want the input wrapped in quotes, but the second does not??
To be clear, there is no variable in my .js file that I defined as foo
. The only reference to foo
that exists in any of my files is this line in html, where foo
is in quotes:
<p id="foo"> this is a paragraph of text </p>
So how come it is being treated like a variable in this line?
var currentP = document.getElementById(foo);