Slashdot Mirror


DOM Scripting

Simon P. Chappell writes "This is an unusual book in a good way. It covers a subject normally the preserve of geeks while being targeted at designers. Not a common approach, but one that Jeremy Keith pulls off rather handily. Mr. Keith is an active member of the Web Standards Project's Scripting Task Force; he not only knows how to script web pages, but he knows how to use that scripting to enhance the page's conformance to standards and even increase a site's accessibility. If you are like me, and have put off working with JavaScript because of the standards issues, then this book is our notification that those days are behind us. If you are a web designer who is interested in using dynamic techniques to enhance your site, but had feared the wrath of the standards police, this book is for you." Read the rest of Simon's review. DOM Scripting author Jeremy Keith pages 341 (12 page index) publisher Apress rating 10/10 reviewer Simon P. Chappell ISBN 1590595335 summary A tour de force that is destined to be called a classic.

I think that it's important to note that this is not a book about Ajax. For those of us feeling overly bombarded with Ajax this and Ajax that, this book is a delightful and refreshing read. Mr. Keith goes beyond the hype and brings us a strong explanation on one of the fundamental pillars of Ajax: working with the Document Object Model (the DOM of the title) using JavaScript. Without DOM Scripting there could be no Ajax, so this is an important addition to the library of any Web Developer who plans to create dynamic Web Applications. Who's it for?

According to the introduction: "This book deals with a programming language, but it isn't intended for programmers. This is a book for web designers. Specifically, this book is intended for standards-aware designers who are comfortable using CSS and XHTML." Mr. Keith is good to his word and his book is wholly targeted at web designers. That being said, I also found that the book was very suitable for programmers, myself included, who have been putting off using JavaScript in any depth. The Structure

The book's structure is fairly standard (no pun intended) and each chapter builds upon the proceeding one. The exceptions to this are the first and last chapters where the history of JavaScript and the future of DOM scripting are discussed, respectively.

Chapter two introduces JavaScript syntax and does a pretty good job considering that it is only 26 pages long. Chapter three then covers the Document Object Model. With the basic concepts of JavaScript and the DOM covered, the rest of the book proceeds to show us how to use them together.

Chapter four works through a basic JavaScript driven image gallery. This gallery is then revisited in chapter six where the JavaScript is upgraded to allow it to degrade gracefully according to the level of JavaScript functionality available in the browser and to ensure that the JavaScript is as unobtrusive as possible. Our final visit to the gallery example is in chapter seven where we learn to create markup on the fly and see how it can be usefully applied to enhance the gallery even further.

Chapter five looks at best practices for web design and how JavaScript and DOM scripting fit into that. Chapter eight takes a break from image galleries and looks at how DOM Scripting can help enhance our existing text content. Enhancement is also the focus of chapter nine, where the intersection and interaction of CSS and the DOM is explored.

Chapter ten is a little bit of fun, taking a look at animation through DOM Scripting. Chapter eleven, called "Putting It All Together" is a case study where a website is created for an imaginary band called "Jay Skript and the Domsters". The name may be corny, but the example is a wonderful display of starting with plain content and enhancing it using only standard compatible techniques. The book wraps up with an appendix of reference information of the JavaScript used in the book. What's to Like?

For a book that is not aimed at programmers, it is a great introduction to programming in JavaScript. Every concept is introduced clearly and the reasoning behind each approach is explained and the justification for it provided.

The book is very comfortable to read. The physical size, the typography, the design and the layout are all excellent. This is not surprising considering the target audience; excellent design is the minimum price of admission to the library of those in the design industry. What's to Consider?

There is very little that I did not like in this book. Although, I think that that it would be useful to point out again, that this isn't specifically written for programmers. If you know JavaScript well, this may not be the book for you. If you have extensive browser scripting experience this may also not be for you. And lastly, if you have no need, desire or interest in standards based scripting, this is absolutely not the book for you.

This is not a reference book. It will teach you a solid core of JavaScript suitable for working with the DOM, but do not think that it will teach you everything that there is to know about JavaScript. While the back of the book does have a small reference section, it is only for the concepts taught in the book. Website

Of course, the book has a website, available at domscripting.com. The site has an active blog and the finished version of the example site for "Jay Skript and the Domsters". Conclusion

This book deserves to be promoted to classic status immediately. It is written clearly, it uses only good principles of programming and adheres strictly to the appropriate standards. What a combination."

You can purchase DOM Scripting from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

76 comments

  1. This is good for everyone. by Spy+der+Mann · · Score: 4, Interesting

    Finally the designer guys will be able to learn basic standards compliant js and stop using the prefabricated, outdated do-not-touch messy scripts that still deal with things like "if(document.all)".

    When I started programming js, I didn't know where to look so i went for the javascript repositories and search for the script I wanted. If I had a book like this one, I would've written it myself.

    And I'm sure that if designers want to delve into the source code, they'll prefer clean, well-intended code rather than the automated (eew) javascript generated by Macromedia^H^H^H^H^H^H^H^H^HAdobe applications.

    Thumbs up :)

    1. Re:This is good for everyone. by possible · · Score: 3, Informative

      Finally the designer guys will be able to learn basic standards compliant js and stop using the prefabricated, outdated do-not-touch messy scripts...

      Unfortunately, Javascripting with DOM is at least an order of magnitude slower than using the non-standard innerHTML approach. This is true of several browsers, including Internet Explorer. At my job, I recently completed an advanced AJAX-based web application interface that contains over 10,000 lines of new (re-usable) JavaScript APIs. DOM is great for small things but when you are rendering a dynamic sortable table with thousands of rows, DOM is absolutely out of the question. The innerHTML approach must be used (not sure why it renders so much faster, but it does).

    2. Re:This is good for everyone. by Spy+der+Mann · · Score: 3, Informative
      Unfortunately, Javascripting with DOM is at least an order of magnitude slower than using the non-standard innerHTML approach.

      That depends on the browser, but i think you're confused. I did NOT mean to replace InnerHTML with DOM. Instead, i talked about replacing stupid code like this:
      if(document.all) document.all['something'] ... else document.layers['something']...


      with code like this:
      document.getElementById('something')...


      Anyway, the book is NOT about AJAX and complicated intranet websites filled with gazillions of forms, but about basic scripting.
    3. Re:This is good for everyone. by Not+The+Real+Me · · Score: 0, Troll

      Well, good for you.

      There's nothing I hate and despise more than a web site that utilizes javascript (or client-side vbscript). By default I turn off scripting in Firefox and Opera. It is truly annoying and incredibly irritating that some web sites are heavily into javascript. Having a website heavily loaded with javascript (that drags the performance of my 1.8 ghz CPU into the toilet and causes it to perform like a Pentium I 60mhz) makes me want to choke the shit out of the imbeciles that created that site.

      What so many of those infactuated with javascript fail to understand is that the web is about getting information out. Not creating a site that is formatted like a fancy textbook with flying windows, music playing in the background and garbage that follows my mouse pointer around the screen.

    4. Re:This is good for everyone. by multipartmixed · · Score: 2, Informative

      Sooo.... you meant that now designers could stop writing code that breaks on anything but IE and Netscape 4?

      The respondent rightly points out that using the W3C DOM still is not the best option for inserting nodes; innerHTML is much faster. To this respondent - the reason is simple: 1,000 row insertions done in the DOM requires 1,000 separate tree insertions and modifications under JavaScript control, marshalling and returning these objects back to the interpreter, blah blah blah. The innerHTML method simply assembles everything as a string first (which is much cheaper!), generates a tree, and inserts the root of the new tree into the document.

      (note, above paragraph somewhat simplied).

      My option? W3C should add a "parse" method, which would parse a hunk of HTML and return a handle to the root node for you to insert yourself.

      --

      Do daemons dream of electric sleep()?
    5. Re:This is good for everyone. by NickFitz · · Score: 1

      Which is precisely the kind of use of JavaScript this book sets out to oppose.

      --
      Using HTML in email is like putting sound effects on your phone calls. Just say <strong>no</strong>.
    6. Re:This is good for everyone. by steinnes · · Score: 2, Informative

      Parent is right, should get modded up.

      The difference lies in the fact that each DOM call results in the whole thing being rendered, whilst the innerHTML method just requires the browser to read a chunk of HTML and render it once.

      Perhaps objects should have some sort of render() method, and a possibility of auto-rendering which could be toggled? Thus avoiding rendering of objects being manipulated after each change, etc? Oh well, it's fun to dream..

    7. Re:This is good for everyone. by Del+Vach · · Score: 1

      var myHTML = ajaxObj.responseText;
      var tmpTag = document.getElementById('hiddenNode');
      tmpTag.innerHTML = myHTML;
      var rootNode = tmpTag.firstChild;

      Think that'd do it.

    8. Re:This is good for everyone. by multipartmixed · · Score: 1

      Of course that'll do it. But you missed the point -- innerHTML is not W3C-blessed (which, frankly, I don't pay a whole lot of attention to, but some people do).

      --

      Do daemons dream of electric sleep()?
    9. Re:This is good for everyone. by multipartmixed · · Score: 2, Interesting

      Oddly enough, IE since version 4 has had a method whose name escapes me at the moment which will do basically what you're asking for. Of course, it exists ONLY in IE.

      Something about updates being buffered off screen or not. Actually, I seem to recall that one of the property values was "onscreen", and the method probably had the word "update" or "refresh" in it.

      --

      Do daemons dream of electric sleep()?
    10. Re:This is good for everyone. by Silas+is+back · · Score: 1

      You have never used Gmail or Flickr or the like, now have you? As the first reply to your post states, this book is not about flying pictures and background-music, this book is about DOM-scripting, the basis of Ajax, which has little to do with your fancy textbook.

      --
      this sig is useless
  2. JavaScript standards??? by MasterC · · Score: 5, Interesting

    ...have put off working with JavaScript because of the standards issues, then this book is our notification that those days are behind us.

    Sorry, but I have to disagree with you immensly on this point.

    There were, and still are, drastic differences between browsers in terms of JavaScript and even DOM. A cursory glance at http://www.quirksmode.org/ shows what I'm talking about.

    Standardizing javascript now, or in the future, has no bearing on supporting the past and present. Unless you can afford to not support browsers... IE doesn't fully support setAttribute() yet (id, class, for, onClick, etc.). Firefox doesn't support innerText, outerHTML, nor outerText. IE doesn't support cssRules but does rules while Firefox is the exact opposite (opera does neither).

    JavaScript has a long ways to go and no book is going to erase these vast differences no matter how well written it is.

    It seems the only way we'll get out of the javascript mess is by everyone supporting everything or an entire new language is created with a strict API defined. Then again, HTML & CSS are still up in the air so standards aren't the whole solution.

    --
    :wq
    1. Re:JavaScript standards??? by Cthefuture · · Score: 4, Insightful

      Having just written a whole bunch of JavaScript, I couldn't agree more and I was thinking the same thing when I read the summary.

      Trying to make stuff work with the various browsers is infuriating. Some things are the same, many things are not, or the behavior is just different enough to drive you insane trying to make everything work.

      As I see it the problem is that the web is more and more becoming an application repository instead of static pictures and text (I know people have been saying this for years and it still applies). I mean that's the whole reason JavaScript and VBscript exist. The issue is that both JavaScript and VBscript are ad-hoc designs done by the major browser makers. We need standards like what ECMA is doing but ECMA doesn't go far enough. They need to define the GUI components and how they work in the scripting language. And the whole system needs to be made more powerful, currently the GUI functionality available in JavaScript/VBscript is substandard.

      XUL sort of tries to solve this problem but again it's defined by a browser maker, good luck trying to get Microsoft to adopt that.

      --
      The ratio of people to cake is too big
    2. Re:JavaScript standards??? by nick_davison · · Score: 4, Insightful

      JavaScript has a long ways to go and no book is going to erase these vast differences no matter how well written it is.

      I disagree.

      You cannot support everything, that is true.

      You can do the following:

      1) Identify a basic starting point (say where browsers had reached n years ago, accepting a high enough percentage of users fit that criteria).

      2) Identify which features are commonly supported across those browsers (or commonly enough) and deem them "safe" to use.

      3) Identify which other features are inconsistent but can gain a consistent interface through your coding. innerText may not be supported but that doesn't mean it's impossible to write consistent setInnerText/getInnerText functions that calls it directly for IE and then does more work to get the same result for other browsers.

      4) Identify which other features are so inconsistent that there is no way you can write your own library to unify them (or add them).

      5) Identify what fail-gracefully methods can be used for older browsers than your cut-off criteria.

      With such an approach, you don't get all features of all implementations of JavaScript and DOM. You do however get a unified interface that allows you to use the majority of features on the majority of browsers and know that, even in the edge cases, the majority of those edge cases will fail gracefully.

      Does it erase all of the differences? Absolutely not. But it does erase enough of them that the barrier for entry for many people now disappears.

      Most people are concerned that they have to learn everything about all inconsistencies before they can code anything. They are concerned that, without that knowledge, even supporting the core browsers becomes impossible and they'll have a massive development cost testing for things they have no idea to look for.

      A solution like the one above lets them have a list of things they can do, things they can't do, and a library of methods to unify the stuff in between. They know that, with that, they're pretty safe.

      And that, as far as most users are concerned, is the unification they need - not absolute unification of every last detail.

    3. Re:JavaScript standards??? by MasterC · · Score: 3, Insightful
      That's a good approach and all, but there are conflicts at some of the most basic function calls like getElementById and getElementsByTagName. The two most basic functions to DHTML: getting elements. quirksmode gives IE an "almost" and "incomplete", respectively. Or how about the nodeType property (IE doesn't bother to set them pre 5.5)? How do you propose working around that? By your proposal, you can't declare any of those "safe"...so, back to my original post, how can you erase these differences with a book? You can't.

      What the entire current JavaScript situation boils down to is the necessity to make libraries that wrap all these functions. Not just for functions that don't exist or don't work right, but inconsistencies in how they work. How about capturing the text that a user has selected? No browser in existance supports the three methods to get that so you have to roll your own that can do all three.

      JavaScript is too diverse and has too many implementations to make your proposal work. A quick rundown:
      • Getting nodes (getElementById & getElementsByTagName): not safe.
      • Setting attributes with setAttribute: not safe.
      • Accessing attributes with attributes[]: not safe.
      • Adding attributes with createAttribute: not safe.
      • Getting attributes with getAttribute: not safe.
      • Adding child nodes with appendChild: not safe.


      So that's getting elements and modifying attributes. That's a bulk of what you do in DHTML. Verdict: not safe.

      Again, a book cannot erase these differences. The only current solution is to make a giant library that handles all these specific cases, but that doesn't get rid of the differences in the language itself at all -- justs masks them from the user.
      --
      :wq
    4. Re:JavaScript standards??? by SparafucileMan · · Score: 2

      I just wrote a cross-browser ajax app with little more than getElementById and innerHTML. Works fine in IE and mozilla with minimal tweaking. Most of it had to do with CSS, not javascript. Also, be careful. JavaScript IS a standard. DOM is a standard. The fact that Mozilla and IE implement the DOMJS link differently isn't part of that. Re: "Just masks them from the user". Exactly. Perfect. Noone cares what your code looks like for the same reason no programmer sits around examining the assembly and machine code his program runs on. Make the library and forget about it. It's not like there aren't good libraries out there already. Browser + DOM + JS + XMLHttpRequest is a beauty and isn't any less powerful or easy for regular apps than any other method. About the only thing it can't handle is a 3D game, so.... *shrug* Maybe you should just write the code and go with the flow instead of analyzing it to death. Nothing is perfect. Ask any VI user.

    5. Re:JavaScript standards??? by Dom2 · · Score: 1
      IE doesn't fully support setAttribute() yet (id, class, for, onClick, etc.). Firefox doesn't support innerText, outerHTML, nor outerText.

      In fairness, setAttribute() is part of the DOM standard, whilst innerText isn't, so I wouldn't be criticising Firefox here.

      Don't fall into the classic trap of "Let's rewrite it and make it better". One rarely does, particularly with an installed base of several billion.

      -Dom

    6. Re:JavaScript standards??? by MasterC · · Score: 1

      Re: "Just masks them from the user". Exactly. Perfect. Noone cares what your code looks like...

      I was referring to the library user (aka the programmer). Not the browser user -- the carelessness is too obvious to bother saying.

      Browser + DOM + JS + XMLHttpRequest is a beauty and isn't any less powerful or easy for regular apps than any other method.

      Extremely wrong on this one. The fundamental flaw with HTTP is that it's purely client-initiated. AJAX is mitigating the "damages" done by this paradigm. Use any real application framework (SDL, Qt, GTK, etc.) and the key difference is bidirectional communcation and initiation.

      For example, doing an instant messager in pure HTML & JS is going to be near impossible. You're guaranteed a lag between pollings (frame/page meta refresh or AJAX) or huge server load to poll every second or less to reduce the lag. With a real application, the data packet comes in, select() wakes up, you process the packet, and display the message. All interrupt driven. You simple cannot do this with a web app.

      The more "regular" you get with an application, the more you need bidirectional initiation. If you're talking an app that doesn't require this (e.g., flickr) then you're peachy.

      Maybe you should just write the code and go with the flow instead of analyzing it to death. Nothing is perfect.

      I'm not claiming JS should be perfect. Analysis leads to debate which leads to resolution. Ignoring a problem does not lead to resolution and nothing is done about it. You're welcome to sit on the sidelines, but that's never been my place so I won't be joining you.

      --
      :wq
    7. Re:JavaScript standards??? by DaggertipX · · Score: 2, Interesting

      I believe the people at www.meebo.com and www.campfirenow.com would disagree with your example. As a user of both of these 'near impossible' services, I can assure you that they do quite well.

    8. Re:JavaScript standards??? by aztracker1 · · Score: 1

      Honestly, if someone hasn't updated a *free* browser in 5 years on their desktop they deserve what they get... ie5.5 came out in 00/01 iirc... nn4.x is equally ancient, and nn7/ff1.0+ work reasonably well... ie6 has more quirks, especially outside of XP... but for the most part, most stuff works in both gecko and ie engines... konqueror/apple-webkit and opera delude things more...

      --
      Michael J. Ryan - tracker1.info
  3. Taco Takedown. by Anonymous Coward · · Score: 0

    "Mr. Keith is an active member of the Web Standards Project's Scripting Task Force; he not only knows how to script web pages, but he knows how to use that scripting to enhance the page's conformance to standards and even increase a site's accessibility."

    So Taco and friends have a copy of this book on their bookshelf?

  4. DOM is hell. by SharpFang · · Score: 2, Informative

    Well, I don't know who was responsible for inventing DOM but I have some experience in writing using it, and today I had a refresher on how ugly it is.
    Consider the following piece of HTML:

    <ul type="square">
    <li><a href="#link1">Page 1</a></li>
    <li><a href="#link2">Page 2</a>(new!)</li>
    </ul>

    Let's rewrite it as DOM:

    var list=document.createElement('ul');
    list.createAttribute('type','square');
    var el1=document.createElement('li');
    var el2=document.createElement('li');
    var link1=document.createElement('a');
    var link2=document.createElement('a');
    link1.createAttribute('href','#link1');
    link2.createAttribute('href','#link2');
    var content1=document.createTextNode('Page 1');
    var content2=document.createTextNode('Page 2');
    var content3=document.createTextNode('(new!)');
    link1.appendChild(content1);
    link2.appendChild(content1);
    el1.appendChild(link1);
    el2.appendChild(link2);
    el2.appendChild(content3);
    list.appendChild(el1);
    list.appendChild(el2);
    document.getElementsByTagName('body')[0].appendChi ld(list);

    Of course you will likely pull link URLs from arrays, texts from some resource file, you won't be creating multiple variables to hold similar elements etc, but to create equivalent piece of document you will likely need to use something very similar to the above. (and it's still not the best. link1.remove(); ? No. link1.parentNode.removeChild(link1); link1.replaceWith(link2)? No. link1.parentNode.replaceChild(link1,link2);

    Do you already feel about the author of DOM specs the way I feel?

    --
    45 5F E1 04 22 CA 29 C4 93 3F 95 05 2B 79 2A B2
    1. Re:DOM is hell. by Anonymous Coward · · Score: 0

      What do you think the API should look like?

    2. Re:DOM is hell. by MemeRot · · Score: 1

      Why would you do it that way? There are multiple sites showing speed tests that demonstrate that standards-compliant dom scripting is the slowest way to dynamically create page content.

      The way I'd do it is load each html snippet into an array with array.push, then join them at the end, and set innerHTML of whatever the container element is to that string. If you know the number of elements up front you can do it even faster by declaring the array with the correct size ahead of time.

      Standards compliance isn't a goal of mine. Writing fast cross-browser compatible code is what matters.

    3. Re:DOM is hell. by Anonymous Coward · · Score: 0

      What about this?
      var list=document.createElement('ul');
      ul.type='squar e';
      var l1=list.appendChild(document.createElement('li'));
      l1.innerHTML="<a href='#link1'>Page 1</a>";
      var l2=list.appendChild(document.createElement('li'));
      l2.innerHTML="<a href='#link2'>Page 2</a>(new!)";

    4. Re:DOM is hell. by graveyhead · · Score: 3, Insightful

      No-one in their right mind writes code like that.

      Generally, the only reason to use DOM for output is when you need to be able to reuse the generated node tree in some other local function, and it is too expensive to use a DOM parser to read in XML data. Client-side in a browser, it is just about *never* too expensive to use a parser instead of code like yours.

      When people do generate DOM like that the calls are generally more spread out inside application code where functions recieve a parent node to append children on.

      Also, why would anyone create 2 <li> elements in inline code? Instead, it seems much more likely that someone would instead be looping over a result set and would be creating 1 <li> per loop.

      You're looking at DOM all wrong. DOM is amazing for scanning through a parsed XML tree. Creating the output tree can be done in a hundred uninteresting ways.

      --
      std::disclaimer<std::legalese> sig=new std::disclaimer; sig->dump(); delete sig;
    5. Re:DOM is hell. by dolphinling · · Score: 1

      And that, kids, is why when you're writing a shopping list, you don't break out GCC, #include <stdio.h>, print each line out, and then make && ./shoppinglist > shoppinglist.txt.

      Instead, you write the shopping list into a file in the first place.

      --
      There are 11 types of people in the world: those who can count in binary, and those who can't.
    6. Re:DOM is hell. by Bogtha · · Score: 4, Informative

      Try this:

      var item, list = document.createElement("ul");
      list.type = "square";
      list.appendChild(item = document.createElement("li"));
      item.appendChild(d ocument.createElement("a"));
      item.lastChild.href = "#link1";
      list.appendChild(item = document.createElement("li"));
      item.appendChild(d ocument.createElement("a"));
      item.lastChild.href = "#link1";
      item.appendChild(document.createTextNod e("(new!)"));
      document.body.appendChild(list);

      That's almost half the size of yours. You're forgetting about the convenience methods and attributes that the DOM provides for HTML documents. As well as that, the various DOM methods have useful return values, so you can create and append elements without the temporary variables you use.

      --
      Bogtha Bogtha Bogtha
    7. Re:DOM is hell. by Anonymous Coward · · Score: 0

      Hell? Ugly? I am sorry, but i can't really see what's so ugly?

      HTML is not a programming language, it's a markup language. Hence, it can be made smaller and more specialized...and better looking(!)... Regarding your parentnodeing example, in another universe i'll bet you'd complain on the lack of .replace(link1, link2).Also, with link1.remove(), it requires an object to have a method to delete itself. Which might be against somebody's beliefs of how a language should work and bla, bla, bla. Just start with the parent instead. I normally do that anyway.

      Thing is that DOM is a quite well thought out, i think. I admit it has it's quirks but remember there were a lot om industry people from different and competing companies and organisations that had to agree.
      Some people are, however, dead set on using it the way it wasn't intended and then whine about the lack of their pet feature.

      BTW. I don't like HTML. Not because it's ugly but because it get's so hard when it grows(where did that disturbing picture come from?). I rather generate large html structures programmatically through DOM than HTML.

    8. Re:DOM is hell. by Anonymous Coward · · Score: 0

      yeah, too bad they were oop people instead of lisp people, eh?

    9. Re:DOM is hell. by 6*7 · · Score: 2, Informative

      "You're forgetting about the convenience methods and attributes that the DOM provides for HTML documents. As well as that, the various DOM methods have useful return values, so you can create and append elements without the temporary variables you use."

      Good advise, I just wonder why you don't follow it yourself?

      You are "hiding" allocation like:
      list.appendChild(item = document.createElement("li"));
      which to my knowledge (and a little testscript) equals:
      item=list.appendChild(document.createElement("li") );

      This is much more readable in your example, now it suddenly becomes very clear where the object, item is a reference, to is changed.

    10. Re:DOM is hell. by Bogtha · · Score: 1

      Oops, I forgot to add the anchor text.

      var item, list = document.createElement("ul");
      list.appendChild( item = document.createElement("li") );
      item.appendChild( document.createElement("a") ).href = "#link1";
      item.lastChild.appendChild( document.createTextNode("Page 1") );
      list.appendChild( item = document.createElement("li") );
      item.appendChild( document.createElement("a") ).href = "#link2";
      item.lastChild.appendChild( document.createTextNode("Page 2") );
      item.appendChild( document.createTextNode("(new!)") );
      document.body.appendChild(list).type = "square";

      Bear in mind that you are creating 11 nodes, so 9 lines of code with 2 variables doesn't seem too bad (definitely not "hell"), it's certainly better than the 19 lines of code with 8 variables you claim is necessary.

      --
      Bogtha Bogtha Bogtha
    11. Re:DOM is hell. by Bogtha · · Score: 1

      I was a bit distracted when I wrote that code. You are right that in many instances,

      foo = bar.appendChild(document.createElement(...))

      ...is more readable than:

      bar.appendChild(foo = document.createElement(...));

      However, a lot of the time you are going to want to add an attribute directly afterwards. With the latter style, you can simply tag it on the end:

      bar.appendChild(foo = document.createElement(...)).baz = "...";

      If you do that with the former style, the variable you are assigning to gets the value of the attribute, not the element you've just created. It's a matter of preference, but I prefer to use the one style throughout rather than chop and change depending on whether I want to add an attribute or not.

      --
      Bogtha Bogtha Bogtha
    12. Re:DOM is hell. by DichotomicAnalogist · · Score: 1

      I do, most definitely. When I was coding with/for DOM, not a week passed without me sacrificing a chicken in an attempt to curse whoever invented DOM to hell. Or at least to using it.

      --
      This troll is over. You can now resume a normal activity.
    13. Re:DOM is hell. by SharpFang · · Score: 1

      Did you read notes on innerHTML in w3c spec?
      Once the code is in place you want to avoid innerHTML like a famine. And if you're doing anything else than HTML (xml? svg?) you don't have innerHTML.

      --
      45 5F E1 04 22 CA 29 C4 93 3F 95 05 2B 79 2A B2
    14. Re:DOM is hell. by SharpFang · · Score: 1

      > list.type = "square";

      Been there, today. Works with HTML but not SVG so if you want to be consistent thorough your app, you're stuck with line.createAttribute('x1',sx);
      It's the same DOM, just different tag names.
      Sure you may contract more stuff into one line. Still 520 bytes of typing vs 105, horrible verbosity and awful syntax.
      I wish innerHTML wasn't so badly broken in the specs.
      body.innerHTML += "....."; and viola. Unfortunately life isn't that easy.

      --
      45 5F E1 04 22 CA 29 C4 93 3F 95 05 2B 79 2A B2
    15. Re:DOM is hell. by SparafucileMan · · Score: 1

      I guess

      document.getElementById('body').innerHTML = "<li><ul type='square'><li><a href='#link1'>Page 1</a></li><li><a href='#link2'>Page 2</a>(new!)</li></ul>"

      was too much of a hassle?

    16. Re:DOM is hell. by corngrower · · Score: 1

      Anyone who would suggest to me that using DOM is a good way to store data internally in a program is a DOM-ASS.

    17. Re:DOM is hell. by SharpFang · · Score: 1

      Try the above with any living document.

      http://msdn.microsoft.com/workshop/author/dhtml/re ference/properties/innerhtml.asp
      When the innerHTML property is set, the given string completely replaces the existing content of the object. If the string contains HTML tags, the string is parsed and formatted as it is placed into the document.

      http://www.mozilla.org/docs/dom/domref/dom_el_ref8 .html
      Note that when you append to the innerHTML of a document, you have essentially created a new document. The session history for the browser is incremented, and when you go Back, the document is there in its original, unappended state.

      Meaning I could just load a separate page instead. innerHTML looks very promising and could be a really great property, but unfortunately the implementation is so tricky and riddled with caveats that using it as anything else than read-only variable will most likely break everything else.

      In your example about the best you could do to avoid the breakage that would occur immediately after applying what you did could be by doing:

      var list=document.createChild('ul');
      list.type="square";
      list.innerHTML="<li><a href=\"#link1\">Page 1</a></li><li><a
      href=\"#link2\">Page 2</a>(new!)</li>";
      document.getElementById('body').appendChild(list);

      This way the innerHTML gets parsed before being inserted into 'list' but 'list' is still 'floating in air', doesn't change anything in existing tree yet, doesn't write to any history, doesn't have any content to be overwritten and so on. Probably. So when it's ready you plant a ready piece of the tree into the document, no re-parsing of HTML of the actual document occurs. Likely. It's not guaranted to behave that way though, so it's just your faith in logical behaviour of the browser that keeps it running.

      --
      45 5F E1 04 22 CA 29 C4 93 3F 95 05 2B 79 2A B2
    18. Re:DOM is hell. by 6*7 · · Score: 1

      "bar.appendChild(foo = document.createElement(...)).baz = '...';"

      Which is offcourse even more unreadable (IMHO). Luckily such contructions can be avoided by some brackets and parentNode, which does little for readability of the actual construction. I'd rather spend some extra characters (mostly whitespace).

      But have you been programming perl by any chance :)

    19. Re:DOM is hell. by hobo+sapiens · · Score: 2, Informative

      Fair enough, but keep in mind that you will seldom need to write that code. I can think of two occasions where I have had to write that much javascript to create nodes (and I do 40 this hours a week), and those were places where I had a form that needed to be expandable to allow users to add any amount of records needed. Then I discovered nice functionality like cloneNode, which does just what it sounds like, copies a node into a var. You can then use insertBefore to place the new node on the page. Usually, I write html code and just clone it as needed.

      Therefore, I suspect that your dislike for Javascript stems from the fact that you may not be familiar with all of its methods and properties. I use this reference frequently. Yes, it is Mozilla, but most of the things here are standard. I'd learn some new methods and properties and then see what you can do with javascript. No, it's not the answer for everything but it can be quite powerful if used correctly.

      I use a lot of Javascript in the intranet environment, which consists of IE6 (sadly), Fx, and Opera. On the internet, yes you are more limited. But as long as you provide alternate, though perhaps less convenient, ways of doing all of the important stuff on your site, you will be OK. Just don't rely on it for _critical_ validation, core functionality and you are OK. For improving usability, efficiency, and user experience in general it is great. It is what it is, but it doesn't have to be as complicated as you make it seem.

      Hope you find that link helpful!

      --
      I am not an actor, but I play one on TV!

      --
      blah blah blah
    20. Re:DOM is hell. by Anonymous Coward · · Score: 0

      You mean did I read this
      http://www.quirksmode.org/dom/innerhtml.html

      Well, sure I could do it the slower way with lot more code, but then again, I wouldn't feel good about myself then :)

      Goold luck creating large amount of dynamic html without it.

    21. Re:DOM is hell. by Anonymous Coward · · Score: 0

      "Goold luck creating large amount of dynamic html without it."

      Yes. Walk the slippery and dangerous (but easy) road because the official one is riddled with holes.
      This SHOULD be easy with DOM, but isn't.

      document.body.append().
      node('ul',{'type':'square'}) . withChildNodes .
              node('li') . withChildNodes .
                        node('a',{'href': '#link1'},'Page 1') .
              endChildNodes .
              node('li') . withChildNodes .
                      node('a',{'href': '#link2'},'Page 2') .
                      textNode('(new!)').
              endChildNodes .
      endChildNodes;

      Cleaner?
      Or a stack, like some other guy did.
      If you read into the specs and other, you'll find innerHTML is NOT a part of any DOM specification. It's a shorthand because DOM was too horrible to write anything serious.

    22. Re:DOM is hell. by Anonymous Coward · · Score: 0

      ------
      Consider the following piece of HTML:

      <ul type="square">
      <li><a href="#link1">Page 1</a></li>
      <li><a href="#link2">Page 2</a>(new!)</li>
      </ul>

      Let's rewrite it as DOM:
      ...
      -----

      That's why Microsoft created XLinq, there you can just use:

      new XElement("ul",
          new XAttribute("type", "square"),
          new XElement("li",
              new XElement("a",
                  new XAttribute("href", "#link1"),
                  "Page 1")),
          new XElement("li",
              new XElement("a",
                  new XAttribute("href", "#link2"),
                  "Page 2"),
              "new!"));

    23. Re:DOM is hell. by Bogtha · · Score: 1

      Works with HTML but not SVG

      Well yes, they are part of the HTML DOM, why would you expect attributes relating to HTML list items to show up in an SVG document?

      you're stuck with line.createAttribute('x1',sx);

      I think you are mixing up DOM1 createAttribute with DOM2 setAttribute.

      It's the same DOM, just different tag names.

      No, it's not the same DOM. Go read the specs, or even my previous comment where I pointed out that HTML documents get special shortcuts.

      Still 520 bytes of typing vs 105

      Wait a sec, you're comparing static HTML to the calls necessary to create that structure with the DOM? Those are two completely different things! One is a static representation of data, one is a script to create such structures dynamically. They aren't alternatives, they are complementary.

      I wish innerHTML wasn't so badly broken in the specs.

      Which specs? And you are aware of DOM3LS, right?

      --
      Bogtha Bogtha Bogtha
  5. I have this book.. by darkmonkeh · · Score: 4, Interesting

    I got given this book for Christmas, and find it is really good at teaching you what to do, and why you should do it. Starting as a "newb" I am now able to integrate AJAX through DOM Scripting - something I would never have dreamed of before.

    Whether you review the book or the "language" is a different matter. I find both excellent, but some may find that while the book is informative and pretty flawless, the language is not all it's cracked up to be. That's another argument, which I'm sure will be brought up soon :p

    1. Re:I have this book.. by warkda+rrior · · Score: 1
      I got given this book for Christmas, [...]
      Me too. Only I received this book for Christmas.
      --
      You need to install an RTFM interface.
  6. Browser delivers apps poorly by robgamble · · Score: 5, Interesting

    The browser is a *TERRIBLE* platform on which to deliver applications. Sure it's convenient to deliver applications on a thin client platform that already has universal install-base, but today's browser still makes this task very clumsy. DHTML is difficult to debug, you must abstract everything into libraries because of browser differences to get any productivity, scripted client-side code runs terribly slow and unless you are willing to bolt other technologies into the mix you must suffer pathetic 1990's-era least-common-denominator UI constructs like radio buttons and check boxes.

    When tools like XUL or XAML truly come online and there are development tools (and debuggers) to support them, thin-client development will get a huge new boost. Until then we will continue to have to "fake it" with clumsy JS and bolt-ons like Applets / ActiveX / Flash / etc.

    --
    No sig for you!
    1. Re:Browser delivers apps poorly by Tablizer · · Score: 2, Insightful

      The browser is a *TERRIBLE* platform on which to deliver applications.

      I generally agree. Browsers started as e-brochure delivery systems but now that we want "real" GUI's, we find browsers have tacked on GUI stuff to this e-brochure framework in a clunky, indirect way.

      However, the browser is becomming sophisticated enough that it can be viewed as a GUI assembler language in which other frameworks can be written on top of it. It has become a fat-client anyhow, so we might as well use it like one to get real GUI's.

      The problem is variance from standards or each other, and versioning problems. However, I think we are now far enough along that we can start to put better GUI frameworks on top of the browser and have good ol' client/server-like apps. We can now think about bringing back the best of VB, Delphi, Clarion, and PowerBuilder like techniques without having to spoon-feed direct HTTP.

    2. Re:Browser delivers apps poorly by temojen · · Score: 2, Insightful
      you must abstract everything into libraries because of browser differences

      Or just distribute a copy of FireFox with your product.

      If the customer isn't willing to install firefox, they're probably not going to install our 6GB of data either.

      scripted client-side code runs terribly slow

      It runs fast enough to serve as an index for our 100,000+ term searchable database. You just have to know how to structure the index files and let the Browser's XML DOM implementation do most of the work for you.

    3. Re:Browser delivers apps poorly by 6*7 · · Score: 1

      "Or just distribute a copy of FireFox with your product.
      If the customer isn't willing to install firefox

      Thanks for supporting the GPs point.

      Just suggest a case where firefox is replaced with latest IE on latest MS OS with latest SP and see what happens.

  7. Sample chapter! :D by Spy+der+Mann · · Score: 3, Informative

    http://domscripting.com/book/sample/

    They talk about graceful degradation, using code like this:

    <a href="http://www.example.com/"
    onclick="popUp(this.href); return false;">Example</a>

    And about progressive enhancement, with code like:

    <p class="warning">
    Be careful!
    </p>

    instead of using font tags.

    Finally, a book which tells you how to do it right from the beginning.

    1. Re:Sample chapter! :D by Zontar+The+Mindless · · Score: 1
      progressive enhancement... graceful degradation...


      It's nice to see somebody pick up on this and appreciate it. It was even more gratifying, when working with the author, to see that he wanted to integrate these ideas into the book from the start, and not just as an afterthought.

      (In case you're wondering, I was the book's technical reviewer.)

      Nice going, Jeremy!
      --
      Il n'y a pas de Planet B.
    2. Re:Sample chapter! :D by great+throwdini · · Score: 2, Informative

      They talk about graceful degradation, using code like this:

      <a href="http://www.example.com/" onclick="popUp(this.href); return false;">Example</a>

      Not to be too picky, but that onclick should really run more along the lines of (as a start):

      onclick="return popUp(this.href)"

      Where popUp() returns true or false depending on whether it actually fired properly. One can never be too careful...

    3. Re:Sample chapter! :D by elementik · · Score: 1

      No - the idea (buzzwordedly entitled HIJAX) is to HIJACK (!) the original function of the A tag and perform a javascript option instead. If javascript is disabled or unavailable, then the original link will fire. They're not trying to get a value from the PopUp function ...

      --
      --- Stop the world! I want to get off!
    4. Re:Sample chapter! :D by great+throwdini · · Score: 1

      No - the idea ... is to HIJACK (!) the... A tag and perform a javascript option instead. If javascript is disabled or unavailable, then the original link will fire. They're not trying to get a value from the PopUp function ...

      I think you're missing a third option: that JavaScript is available, but popUp() doesn't work as intended. In the case of the original, nothing would happen. There's no telling what popUp() attempts, and so, there's no guarantee from generalized parsing of a call that it will succeed such that the original link shouldn't be navigated to instead.

      And so, the small tweak offered. Trust me, you want to return the value of false (in this case, the measure of success) from the function rather than offering it regardless of outcome.

  8. Stack helper class. by temojen · · Score: 1

    This is why I have a stack helper class. For me it looks like:

    ds = new DOMStack( "containerdivname" );

    ds.push( "ul" );
    ds.setAtt( "type" , "square" );

    ds.push( "ul" );
    ds.pushA( "#link1" , "Page 1" );
    ds.popInto( ); ds.popInto( );

    ds.push( "ul" );
    ds.pushA( "#link2" , "Page 2" );
    ds.popInto( );
    ds.pushText( "(new!)" );
    ds.popInto( );

    ds.popInto( );

    Except that it's almost never hardcoded, or I'd just write it in HTML in the first place.

    (and I've chucked in a bunch of semantics-neutral whitespace to keep slashdot from inserting sematics-changing whitespace)

  9. dummy, you spelled DOOM wrong by jeddak · · Score: 1

    oops

  10. Consider browser tech... by Kozz · · Score: 1

    When a browser/OS combination determines how something renders, like an input type="file" element. Want to stylize it? The page at http://www.quirksmode.org/dom/inputfile.html provides some guidance, but holy crap, what a friggin pita!

    [this I know, spending a few hours trying to maybe write my own version with no better luck]

    --
    I only post comments when someone on the internet is wrong.
  11. Question for Reviewer by Comatose51 · · Score: 0, Offtopic
    I have a project where I need to script or develop a way of scripting the login and download of certain web sites. A developer suggested looking into DOM for my project. I haven't found many books on DOM and none on using it to script interactions with a website. While this is not the subject of this book, do you think it can help me navigate my way to completing my project?

    Thanks.

    If anyone has a good idea on how to automatically (or mostly automatically) generate a script to login and download data from a website, please let me know. Thanks.

    --
    EvilCON - Made Famous by /.
    1. Re:Question for Reviewer by drgonjo · · Score: 1

      Talk to a hacker not a designer and JS is not the hacker's weapon of choice. You're barking up the wrong tree.

    2. Re:Question for Reviewer by multipartmixed · · Score: 1

      The developer you talked to is an idiot.

      Either script wget or Lynx and extract your pr0n passwords with sed, awk, or perl. Piece of cake.

      --

      Do daemons dream of electric sleep()?
  12. Dom Scripting and AJAX by FloridaFun · · Score: 4, Informative

    Take a look at this AJAX DOM Scripting web site http://www.gendivide.com/ . It appears to offer alot of dynamic functionality. Very fast. Doesn't like old people though.

    1. Re:Dom Scripting and AJAX by Anonymous Coward · · Score: 0

      Doesn't work with javascript disabled.

    2. Re:Dom Scripting and AJAX by Anonymous Coward · · Score: 0

      >> Take a look at this AJAX DOM Scripting web site

      FYI, AJAX = Asynchronous Javascript And XML. It therefore doesn't work with javascript disabled.

  13. Good webdesigners know the DOM by drgonjo · · Score: 2, Insightful

    Its my experience that good web designers have learned to use the DOM quite well. Granted they started by patching together examples from http://alistapart.com/ to make their CSS more flexible and cross browser, but as it stands today, at least at my company, we differ to the designers for most DOM scripting. We only hire CSS/Standards based designers so that likely contributes to our technicaly savvy design team, but when the C# guys admit that the design kids are better suited to front-end scripting tasks that speaks volumes. So next time you cop out and limit your app for fear of unsolvable x-browser issues remember that 19 year old kids fresh out of design school are pulling it off everyday. On a side note... don't say DHTML... we're in the age of CSS, AJAX and unobtrusive JS... DHTML was the age of .

  14. Suckage by andy_shepard · · Score: 1

    But what if I've put off working with Javascript because of the suckage issue?

    1. Re:Suckage by tinkertim · · Score: 2, Insightful

      Suck is a harsh word for such a massive (and broadly useful) language. I think where you could imply suckage (and where I pinned my JS leaning frustrations) is the quality of code you were studying to learn. Snippets .. I learn best from examples.

      I'm correct in saying for the majority of us, if we want to learn a language we go looking for snippets dissect them get an understanding then add it to working knowledge. I have had such a hard time finding any 2 JS authors who agree on anything that I kind of just stopped persuing it.

      The advent of those "article wiki" search engine traps did not help bring any clarity. What I mostly found were groups of people fighting over the "right" way to do it with no apparent victor. It wasn't apathy that stopped me it was total confusion. I wanted to learn only once if possible .. so I waited.

      Double suckage : Now my clients want inter-operable AJAX and I can't guess my way through it. I make server control panels and network monitoring applications. I *have* to learn this stuff.

      It's not Javascript's fault for existing. It's my fault for not continuing to play with JS while waiting for w3c and others to glue everything together.

      Ugh this is going to hurt.