Jump to content

Dynamically Creating A New Dom Element


Opv
 Share

Recommended Posts

I am attempting to learn the learn more about creating and populating new DOM elements using javascript. The W3S tutorial is helpful but the examples seem to require an element to already exist before new text can be appended, etc.I am curious to know whether it is possible to take a blank HTML document (with just the html, head, title and body tags) and dynamically create new elements and then populate those elements in the same script. I tried (unsuccessfully, I might add):newEl = document.createNode("div");newEl.setAttribute("id", "content");txt = document.createTextNode("This is some text.");newEl.appendChild(txt);Is something like this possible?

Link to comment
Share on other sites

It is certainly possible. You got off to the wrong foot with createNode(), since that is a method used with XML, not HTML. You also need to append the new node to something, just as you correctly appended the text node. But you're close. Try this (I haven't tried this in IE--appending to the body might not work there--don't know):newEl = document.createElement("div");newEl.setAttribute("id", "content");txt = document.createTextNode("This is some text.");newEl.appendChild(txt);document.body.appendChild(newEl);

Link to comment
Share on other sites

It is certainly possible. You got off to the wrong foot with createNode(), since that is a method used with XML, not HTML. You also need to append the new node to something, just as you correctly appended the text node. But you're close. Try this (I haven't tried this in IE--appending to the body might not work there--don't know):newEl = document.createElement("div");newEl.setAttribute("id", "content");txt = document.createTextNode("This is some text.");newEl.appendChild(txt);document.body.appendChild(newEl);
Thanks. That seems to work in both Firefox and IE7.
Link to comment
Share on other sites

Good. And it's good you're learning DOM methods. Just be aware that for the time being, they are mostly slower than using dot notation or innerHTML. In some cases, quite a bit slower. Not a big deal if you want to create a few elements at a time. But imagine you wanted to create a grid of 50 x 50 text inputs that way. Depending on how many attributes you assigned, you might notice a time lag of several seconds.:)

Link to comment
Share on other sites

Good. And it's good you're learning DOM methods. Just be aware that for the time being, they are mostly slower than using dot notation or innerHTML. In some cases, quite a bit slower. Not a big deal if you want to create a few elements at a time. But imagine you wanted to create a grid of 50 x 50 text inputs that way. Depending on how many attributes you assigned, you might notice a time lag of several seconds.:)
Thanks. I've been using innerHTML for a while now and find it shorter and easier. However, I got the impression from one site I was reading that DOM methods were preferable to using innerHTML. Or, it might have been "document.write(...) that was being discouraged. I forget. Anyway, that's what prompted me to start looking into DOM methods.
Link to comment
Share on other sites

Thanks. I've been using innerHTML for a while now and find it shorter and easier. However, I got the impression from one site I was reading that DOM methods were preferable to using innerHTML. Or, it might have been "document.write(...) that was being discouraged. I forget. Anyway, that's what prompted me to start looking into DOM methods.
Deirdre's Dad won't argue about document.write being discouraged.
Link to comment
Share on other sites

Deirdre's Dad won't argue about document.write being discouraged.
I don't have any feeling about that either way. I'm not averse to learning new things; I just like to understand why one procedure is preferred over the other. For example, I've learned css styling, but I still don't understand why "style="font-weight:bold" is preferred over the old <b>...</b>. That seemed so simple to me. I presume there are reasons that are over my head.As to my original inquiry pertaining to DOM, if DOM methods are preferred over innerHTML, I'd love to know why. It makes learning the new procedure more meaningful to know why I need to learn it.
Link to comment
Share on other sites

why "style="font-weight:bold" is preferred over the old <b>...</b>.
Under a pure DOM model, every page tag should name a page element, that is, an object. A div is an object, and paragraph is an object, a button is an object, etc. Bold is a property. It gets applied to the text within an object, but it is not an object itself. So, convenient or not, it doesn't fit the model. And of course we want our model to make as much logical sense as possible.FWIW, style="font-weight:bold" is only a little better. Ideally the font-weight would be defined in a style sheet.
. . . if DOM methods are preferred over innerHTML, I'd love to know why.
Philosophically, this comes down to the same thing. Commitment to an Object Model means that we should be creating and manipulating objects, which is what the DOM methods allow us to do. Writing innerHTML just means you're writing text. The DOM is now obliged to parse the text and add the object to the model on its own.Mostly it's a difference in attitude. But having an object-oriented attitude comes in handy in related matters. Say you wanted to insert a new <div> between two existing ones. innerHTML won't help you. Thinking of your page as a bunch of text won't help you. Realizing that a <div> is an object might lead you to suspect that there is a method for inserting a new object somewhere. And there is. Same if you want to remove an object. If all you think about is text, you might be led to do something silly, like treating your whole document like a string, doing a substring search for opening and closing tags, playing with indexes, removing text, etc. Yecch. element.parentNode.removeChild(element) does the same thing with no fuss at all. But I'm only aware of it because I'm in a DOM frame of mind.Maybe that stirs your brain a little. :)[slightly edited.]
Link to comment
Share on other sites

Under a pure DOM model, every page element (everything named a <tag> ) should be a page element, that is, an object. A div is an object, and paragraph is an object, a button is an object, etc. Bold is a property. It gets applied to the text within an object, but it is not an object itself. So, convenient or not, it doesn't fit the model. And of course we want our model to make as much logical sense as possible.FWIW, style="font-weight:bold" is only a little better. Ideally the font-weight would be defined in a style sheet.Philosophically, this comes down to the same thing. Commitment to an Object Model means that we should be creating and manipulating objects, which is what the DOM methods allow us to do. Writing innerHTML just means you're writing text. The DOM is now obliged to parse the text and add the object to the model on its own.Mostly it's a difference in attitude. But having an object-oriented attitude comes in handy in related matters. Say you wanted to insert a new <div> between two existing ones. innerHTML won't help you. Thinking of your page as a bunch of text won't help you. Realizing that a <div> is an object might lead you to suspect that there is a method for inserting a new object somewhere. And there is. Same if you want to remove an object. If all you think about is text, you might be led to do something silly, like treating your whole document like a string, doing a substring search for opening and closing tags, playing with indexes, removing text, etc. Yecch. element.parentNode.removeChild(element) does the same thing with no fuss at all. But I'm only aware of it because I'm in a DOM frame of mind.Maybe that stirs your brain a little. :)
Very meaningful explanation. Thanks.
Link to comment
Share on other sites

Let me just reiterate what was being said, because I'm not sure a clear "it's best that..." asnwer was given:If possible, use innerHTML, as it's often (maybe not always, but often) considerably faster. It's also very convinient.In cases it's not possible to use innerHTML directly, like the mentioned "insert a div between two existing ones" case, use DOM methods. "Using directly" also means that you avoid assembling a string to later innerHTML (it's dirty, and usually kills the performance benefit).If you want to alter an attribute, use the HTML DOM objects OR make a test to see if HTML DOM is faster than XML DOM for your case. In most cases, HTML DOM is slightly faster.Whatever you do, NEVER, EVER, use document.write().

Link to comment
Share on other sites

Just adding to Robot's addition:innerHTML has limitations, especially in IE. You cannot use it to add options to a select element, for example. You must use select.add(), and even that is used differently by IE than everyone else. Another: You cannot create a list (like <ul>) using innerHTML. You must use document.createElement() and element.addChild().The frustrating thing is, MSIE invented innerHTML. But IE is the browser where it works least consistently.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...