get an element by id does not work!

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • webEater

    get an element by id does not work!

    I have a problem, it's not browser specific, and I don't get a
    solution. I have an (X)HTML document, I show you a part of it:

    ....
    <!--<div class="pad">-->

    <div id="eventImages "><img src="" id="eventImage0 "
    class="eventIma ge"><img src="" id="eventImage1 "
    class="eventIma ge"></div>

    <div id="eventRightM enu">
    <a href="javascrip t:" class="eventIco n"
    style="float:le ft;">&lt;</a>
    <a href="javascrip t:" class="eventIco n"
    style="float:le ft;">&gt;</a>
    <a href="javascrip t:" class="eventIco n"
    style="float:le ft;">L+</a>
    </div>

    <div id="eventMaps"> </div>

    <!--</div>--></div>

    ....

    So after the whole document has been loaded (including JS etc), I want
    to get an element by Id, for all elements it works properly, but for
    'eventImage0', 'eventImage1' and any other children of 'eventImages' it
    does not work. My Firebug just says undefined when I put
    $('eventImage0' ) or null by using
    document.getEle mentById('event Image0'));

    Can somebody help me? This behaviour is not what I am used to. IE and
    FF do the same, so whats wrong?

    Greetz,
    Andi

  • RobG

    #2
    Re: get an element by id does not work!

    webEater wrote:
    I have a problem, it's not browser specific, and I don't get a
    solution. I have an (X)HTML document, I show you a part of it:
    Your document seems to be plain HTML.
    >
    ...
    <!--<div class="pad">-->
    >
    <div id="eventImages "><img src="" id="eventImage0 "
    Use 2 or 4 spaces for indents, manually wrap code at about 70
    characters to make it easily readable and prevent possible
    auto-wrapping errors.
    class="eventIma ge"><img src="" id="eventImage1 "
    class="eventIma ge"></div>
    For valid XHTML, close img tags:

    <img ... />

    >
    <div id="eventRightM enu">
    <a href="javascrip t:" class="eventIco n"
    The href attribute should have a real value, not some random text.
    style="float:le ft;">&lt;</a>
    <a href="javascrip t:" class="eventIco n"
    style="float:le ft;">&gt;</a>
    <a href="javascrip t:" class="eventIco n"
    style="float:le ft;">L+</a>
    </div>
    >
    <div id="eventMaps"> </div>
    >
    <!--</div>--></div>
    There appears to be a closing div tag here but no matching opening tag.
    >
    So after the whole document has been loaded (including JS etc), I want
    to get an element by Id, for all elements it works properly, but for
    'eventImage0', 'eventImage1' and any other children of 'eventImages' it
    does not work. My Firebug just says undefined when I put
    $('eventImage0' ) or null by using
    The use of $() infers the use of the Prototype.js library, help for
    that should be sought from an appropriate news group.

    document.getEle mentById('event Image0'));
    That should work fine provided the DOM elements exist. What do you see
    in the DOM inspector? The following works fine for me:


    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    <title>foo</title>
    <script type="text/javascript">
    window.onload = function(){
    alert(document. getElementById( 'eventImage0')) ;
    }
    </script>

    <div id="eventImages "><img src="" id="eventImage0 " alt="foo"
    class="eventIma ge"><img src="" id="eventImage1 " alt="foo"
    class="eventIma ge"></div>


    --
    Rob

    Comment

    • Matt Kruse

      #3
      Re: get an element by id does not work!

      RobG wrote:
      The use of $() infers the use of the Prototype.js library
      Or a number of others, including one I'm working on for my own use and
      possible future release.

      In spite of the protests of Richard et al, $() is becoming the "defacto
      standard" selector function to replace and augment
      document.getEle mentById(). IMO.

      --
      Matt Kruse




      Comment

      • Peter Michaux

        #4
        Re: get an element by id does not work!


        Matt Kruse wrote:
        RobG wrote:
        The use of $() infers the use of the Prototype.js library
        >
        Or a number of others, including one I'm working on for my own use and
        possible future release.
        >
        In spite of the protests of Richard et al, $() is becoming the "defacto
        standard" selector function to replace and augment
        document.getEle mentById(). IMO.
        Matt you might be interested in this link

        <URL: http://www.danwebb.net/2007/1/10/scripting-essentials>

        Peter

        Comment

        • RobG

          #5
          Re: get an element by id does not work!


          Matt Kruse wrote:
          RobG wrote:
          The use of $() infers the use of the Prototype.js library
          >
          Or a number of others, including one I'm working on for my own use and
          possible future release.
          >
          In spite of the protests of Richard et al, $() is becoming the "defacto
          standard" selector function to replace and augment
          document.getEle mentById(). IMO.
          I understand Richard's primary complaints, I think they are:

          - the use of the $ character should indicate machine-generated code
          - getElementById really doesn't need to be abbreviated
          - the name is meaningless

          I think, on their own, those arguments are good ones. For me, the use
          of $ brings back memories of TECO (a VMS line editor) and korn shell
          scripting - some good, some bad.

          But the argument about abbreviation doesn't hold up when you realise
          that Prototype uses the $() function for more than just an alias for
          getElementById - it is an essential part of Prototype as it ensures the
          the returned object is a Prototype-extended DOM element, not just a
          plain vanilla DOM element. An alternative, meaningful name might be
          'getExtendedPro totypeDOMObject ' or similar.

          As a result, just about every single function in Prototype that has a
          DOM element or id as a formal parameter starts with:

          el = $(el);

          even where that results in the same object being passed to $() several
          times by different methods in a single program sequence. So I guess if
          some other longer function name was used, the amount of code would
          increase quite a bit.

          Given that a short name is more easily misunderstood than a longer more
          descriptive name, using a totally meaningless symbol might be
          considered a good idea as it ensures nothing is inferred by the name.
          However, an issue arises here because the chosen symbol already has a
          purposed suggested in the ECMAScript Language specification. Also,
          even though the name is otherwise meaningless, there is no easily
          discoverable documentation telling you the importance of $() to the
          whole library.

          So when $() is encountered in a code snippet with no other context,
          which library are we to assume is in use, and what purpose is it
          supposed to fulfil? Though in this case, we can at least infer that it
          is some kind of getElementById replacement. My guess was from
          Prototype, no doubt there are others. :-)


          --
          Rob

          Comment

          • Jim Land

            #6
            Re: get an element by id does not work!

            "RobG" <rgqld@iinet.ne t.auwrote in news:1168923230 .208540.263760
            @v45g2000cwv.go oglegroups.com:
            For me, the use
            of $ brings back memories of TECO (a VMS line editor)
            TECO is a text editor/programming language so ancient that it predates
            even vi and emacs. It was introduced by DEC in the 1960s when punched
            paper tape was a common storage medium and PDP model numbers were still
            in the single digits.

            To save space, TECO assigns a command to each character. A program
            written in TECO "more closely resembles transmission line noise than
            readable text."[1]

            We have come a long way since the PDPs --- storage space is now cheap and
            plentiful. Let us be thankful that we can freely use names, properties,
            and methods that tell us something meaningful and make our code readable.

            Remember, you are not the only person who will eventually dig into your
            code and revise it.

            [1] http://en.wikipedia.org/wiki/Text_Editor_and_Corrector

            Comment

            • VK

              #7
              Re: get an element by id does not work!

              RobG wrote:
              I understand Richard's primary complaints, I think they are:
              >
              - the use of the $ character should indicate machine-generated code
              Can anyone produce a single sample of "machine-generated code" in
              application to javascript? Say if I have
              <script type="text/javascript">
              <!-- CGI script -->
              </script>
              then it is machine-generated and $identifiers are OK? But if I save
              this script in .js file so use later as
              <script type="text/javascript" src="savedSourc e.js"></script>
              then $identifiers are bad and I have to replace them all?
              :-)

              When Brendan Eich was making JavaScript out of LiveScript one of
              requests was to make JavaScript more Java-looking because everything
              with "Java" was hot stuff that time.
              It was reflected not only in syntax but in specs as well. In Java
              during parsing custom classes are being saved in automatically created
              files $CustomClass1.c lass, $CustomClass2.c lass where the name of custom
              class is auto-prefixed by $
              In JavaScript "machine-generated code" doesn't have and never had any
              practical sense. It is just a "beautifyin g" string in specs to please
              the eyes of potential Java-readers. Anyone feel free to disregard.

              Comment

              • Matt Kruse

                #8
                Re: get an element by id does not work!

                RobG wrote:
                I understand Richard's primary complaints, I think they are:
                - the use of the $ character should indicate machine-generated code
                That's a suggestion in the specs. Certainly not law. The _vast_ majority of
                people writing javascript have never seen the specs, nor do they care that
                they suggest $-prefixed names be reserved for machine-generated code.
                - getElementById really doesn't need to be abbreviated
                It's quite a long name, and limited in its functionality. You cannot select
                multiple items with one call, for example. The purpose of $() is not just to
                replace document.getEle mentById() but also to extend it to be more useful.
                - the name is meaningless
                I don't think so. It's short for "Selector" and $() is better than S(), IMO.
                An alternative, meaningful name might be
                'getExtendedPro totypeDOMObject ' or similar.
                I think that all libs should have a "full" name, and then also $(). If
                someone is uncomfortable using $(), then use the full name. But why waste
                all that typing?
                However, an issue arises here because the chosen symbol already has a
                purposed suggested in the ECMAScript Language specification.
                Does that really matter? When more people understand the purpose of $() than
                have even heard of the specs, then I say the specs lose. Too bad.
                So when $() is encountered in a code snippet with no other context,
                which library are we to assume is in use, and what purpose is it
                supposed to fulfil?
                We don't know exactly. But I would say almost everyone here knows that
                $('id') will get a reference to an element with id "id", regardless of which
                framework has implemented the $() function. That's knowledge that's in the
                world, and that's useful.

                --
                Matt Kruse




                Comment

                • Richard Cornford

                  #9
                  Re: get an element by id does not work!

                  VK wrote:
                  RobG wrote:
                  >I understand Richard's primary complaints, I think they are:
                  >>
                  > - the use of the $ character should indicate machine-generated code
                  >
                  Can anyone produce a single sample of "machine-generated code"
                  in application to javascript?
                  There is an obvious contradiction in asking "anyone" to produce
                  something that is, by definition, produced by a machine. If you mean can
                  someone post code that was machine generated then yes, I can, though I
                  don't see where that will get you:-

                  var $FieldEvents = {
                  'RS_TYPE.ERESRC .DEFAULTS':{
                  onDblClick:[
                  {
                  lookUp:['RS_TYPE@EQUAL@ RS_TYPE.ERESRC. DEFAULTS']
                  }
                  ],
                  onChange:[
                  {
                  validate:['RS_TYPE@EQUAL@ RS_TYPE.ERESRC. DEFAULTS','LFLD ']
                  }
                  ]
                  }
                  };

                  This is one of (currently) 700-odd machine generated JS files that vary
                  in complexity and size from about 20KB to 0KB (as it is faster for the
                  server to find and return an empty file than it is for it to fail to
                  find one and return a 404 error).

                  Say if I have
                  <script type="text/javascript">
                  <!-- CGI script -->
                  </script>
                  then it is machine-generated and $identifiers are OK?
                  Yes, but not only OK, they are advisable as it will help (thus speed the
                  work of) someone wishing to fix problems in the generated code to know
                  that they should be going to the machine that generates the code (or the
                  data that it is generated from) to fix the problems.
                  But if I save
                  this script in .js file so use later as
                  <script type="text/javascript" src="savedSourc e.js"></script>
                  then $identifiers are bad and I have to replace them all?
                  :-)
                  That would depend on your reasons for doing so. If having the CGI
                  generate and output the script and then transferring it into a static
                  file is the intended manufacturing process for the static JS file, and
                  will (or may) be repeated in future, then leaving the lading $ symbols
                  in place is a good idea as it will tip any potential editors of the file
                  off that they are working on the wrong subject and should be looking to
                  the code that generated the file (or the data it was generated from), as
                  any modifications they make to the file itself will be undone the next
                  time it is generated.

                  If there is no intention to ever re-create the file with the machine,
                  and direct human editing is expected, then leading $ symbols would
                  become misleading (and probably should not have been included in the
                  first place).
                  When Brendan Eich was making JavaScript out of LiveScript
                  one of requests was to make JavaScript more Java-looking
                  because everything with "Java" was hot stuff that time.
                  Can you back that assertion up at all? Or did it come 'off the top of
                  you head' as usual?
                  It was reflected not only in syntax but in specs as well.
                  When LiveScript became JavaScript there was no public specification of
                  the language.
                  In Java during parsing custom classes are being saved in
                  automatically created files $CustomClass1.c lass,
                  $CustomClass2.c lass where the name of custom class is
                  auto-prefixed by $
                  In JavaScript "machine-generated code" doesn't have and
                  never had any practical sense.
                  Just because working on a system that uses machine generated javascript
                  is out of your league (by a very long way) it does not follow that there
                  is no machine generated javascript, or that using it "never had any
                  practical sense".
                  It is just a "beautifyin g" string in specs to please
                  the eyes of potential Java-readers. Anyone feel free
                  to disregard.
                  Conventions in programming languages have purpose, if appropriately
                  employed they can increase the reliability of the code written, and
                  introduce clarity and implied meaning into the source code that reduces
                  ongoing maintenance costs.

                  From your point of view, as someone who can barely string 30 lines of
                  code together and come up with something effective (or tell how
                  effective that something is once you have written it (let alone know
                  what the code you have written is doing, or explain what you thought it
                  was doing)(see:-

                  Message-ID: <1137265131.410 715.21820@o13g2 000cwo.googlegr oups.com>
                  Message-ID: <1137408334.333 670.241000@g14g 2000cwa.googleg roups.com>
                  Message-ID: <1137446151.114 174.311220@g49g 2000cwa.googleg roups.com>
                  Message-ID: <1158172654.173 106.100790@e3g2 000cwe.googlegr oups.com>
                  Message-ID: <1168268328.918 759.100270@i15g 2000cwa.googleg roups.com>
                  Message-ID: <1166481104.031 648.25300@l12g2 000cwl.googlegr oups.com>
                  - and countless other examples (pretty much everything you have ever
                  posted that either contained code or talked about javascript).

                  )), where your preferred approach is invariably the worst available and
                  often orders of magnitude more complex than is necessary, any absence of
                  code clarity is probably in your best interest (as it will act to keep
                  observers from seeing how inept you are) and any increase in ongoing
                  maintenance costs is a drop in the ocean next to the burden of the costs
                  that follow from letting you work in web development in the first place.

                  Richard.


                  Comment

                  • webEater

                    #10
                    Re: get an element by id does not work!

                    RobG schrieb:
                    webEater wrote:
                    I have a problem, it's not browser specific, and I don't get a
                    solution. I have an (X)HTML document, I show you a part of it:
                    >
                    Your document seems to be plain HTML.
                    This is right. Later I will convert it into XHTML.

                    ...
                    <!--<div class="pad">-->

                    <div id="eventImages "><img src="" id="eventImage0 "
                    >
                    Use 2 or 4 spaces for indents, manually wrap code at about 70
                    characters to make it easily readable and prevent possible
                    auto-wrapping errors.
                    OK.
                    class="eventIma ge"><img src="" id="eventImage1 "
                    class="eventIma ge"></div>
                    >
                    For valid XHTML, close img tags:
                    >
                    <img ... />

                    <div id="eventRightM enu">
                    <a href="javascrip t:" class="eventIco n"
                    >
                    The href attribute should have a real value, not some random text.
                    I tried it out but this is not a solution for my problem.
                    style="float:le ft;">&lt;</a>
                    <a href="javascrip t:" class="eventIco n"
                    style="float:le ft;">&gt;</a>
                    <a href="javascrip t:" class="eventIco n"
                    style="float:le ft;">L+</a>
                    </div>

                    <div id="eventMaps"> </div>

                    <!--</div>--></div>
                    >
                    There appears to be a closing div tag here but no matching opening tag.
                    How I said, it's just a part of my page.

                    So after the whole document has been loaded (including JS etc), I want
                    to get an element by Id, for all elements it works properly, but for
                    'eventImage0', 'eventImage1' and any other children of 'eventImages' it
                    does not work. My Firebug just says undefined when I put
                    $('eventImage0' ) or null by using
                    >
                    The use of $() infers the use of the Prototype.js library, help for
                    that should be sought from an appropriate news group.
                    Correct, I use prototype 1.5.0.
                    document.getEle mentById('event Image0'));
                    >
                    That should work fine provided the DOM elements exist. What do you see
                    in the DOM inspector? The following works fine for me:
                    Thank for this tip, Rob! After using a method I removed the child
                    elements by mistake. Of course it was my fault. Thank you for your
                    effort!
                    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
                    "http://www.w3.org/TR/html4/strict.dtd">
                    <title>foo</title>
                    <script type="text/javascript">
                    window.onload = function(){
                    alert(document. getElementById( 'eventImage0')) ;
                    }
                    </script>
                    >
                    <div id="eventImages "><img src="" id="eventImage0 " alt="foo"
                    class="eventIma ge"><img src="" id="eventImage1 " alt="foo"
                    class="eventIma ge"></div>
                    >
                    >
                    --
                    Rob

                    Comment

                    • Richard Cornford

                      #11
                      Re: get an element by id does not work!

                      Matt Kruse wrote:
                      RobG wrote:
                      >I understand Richard's primary complaints, I think they are:
                      > - the use of the $ character should indicate machine-generated
                      >code
                      >
                      That's a suggestion in the specs. Certainly not law.
                      The spec says "The dollar sign is intended for use only in mechanically
                      generated code", which is neither a suggestion nor an order, it is an
                      explanation of why a character that did not need to be included has been
                      included.
                      The _vast_ majority of people writing javascript have never seen
                      the specs, nor do they care that they suggest $-prefixed names be
                      reserved for machine-generated code.
                      It is not just as a prefix that the dollar symbol has that implied
                      meaning.
                      > - getElementById really doesn't need to be abbreviated
                      >
                      It's quite a long name, and limited in its functionality. You cannot
                      select multiple items with one call, for example. The purpose of $()
                      is not just to replace document.getEle mentById() but also to extend
                      it to be more useful.
                      >
                      > - the name is meaningless
                      >
                      I don't think so. It's short for "Selector" and $() is
                      better than S(), IMO.
                      Being short for something does not make it meaningful. It is necessary
                      to know what it is short for and how it is 'short' for it if it is that
                      much of an abbreviation. You can just about work out something like
                      'gEBI', but a single character really needs knowing up front.

                      Why would "Selector" be a name for a wrapper round - getElementById -?
                      Why would - $ - be a better abbreviation than 'S'? And if - $ - is to be
                      an abbreviation wouldn't it be better suited as an abbreviation of
                      'dollar', applied to a function that, say, took a numeric argument and
                      returned a formatted US currency string?

                      <snip>
                      >However, an issue arises here because the chosen symbol
                      >already has a purposed suggested in the ECMAScript Language
                      >specificatio n.
                      >
                      Does that really matter?
                      Yes it does matter. The existing convention is a useful convention. It
                      allows more to be inferred from source code than is written in the
                      source code.
                      When more people understand the purpose of
                      $() than have even heard of the specs,
                      "Understand " is an interesting choice of word. How many propel have you
                      encountered who really understand javascript and who haven't at least
                      heard of ECMA 262?

                      But we both know the real reason that - $ - is used in Prototype.js, and
                      similarly in other places. It is because in some language preceding a
                      variable name with a dollar symbol means; 'take the value of this
                      variable as the name of another variable and return the value of that
                      other variable'. Thus - $x; - has its nearest equivalent in javascript
                      as - eval(x); -(at least when the value of - x - holds the name of a
                      variable/function/formal parameter defined in the current scope (or
                      maybe - window[x] - if the only significant scope for the operation is
                      global)). If you could do - var $ = eval; - and then call it as -
                      $(x); - (which you cannot as eval may throw an EvalError exception if
                      called in any way other than by the explicit use of its name as an
                      Identifier) that formulation would most closely satisfy the
                      'understanding' of individuals familiar only with those languages.

                      var $ = window; - or - var $ = this; -(in the global execution context),
                      used with - $[x]; - might be the other alternative, though it is
                      unlikely that either would fully satisfy the expectations of someone
                      familiar with - $x; - from other languages. (and they are the ones to
                      whom Prototype.js seems to have the greatest appeal).

                      In practice wrapping a - $ - function around - getElementById - (however
                      loosely) is more of a nod toward the Microsoft notion that IDed DOM
                      elements should be made available as properties of the global object
                      (effectively pre-defined global variables). That decision by Microsoft
                      has been widely perceived as a poor choice, and promoting to conceptual
                      relationship between IDed DOM elements and global variables through the
                      borrowing of meaning associated with the dollar symbol in other
                      languages does not strike me as a good idea at all.

                      Incidentally, it is the disregard of the provision for throwing
                      EvalError exceptions that makes the current version of Prototype.js
                      (needlessly) non-ECMAScript compliant. We can see from their disregard
                      for its naming conventions that the authors of Prototype.js were not
                      familiar with the language specification, and we know that less skilled
                      javascript authors don't tend to push their browser testing beyond the
                      most common sub-set of browsers and so don't get to see how disregarding
                      the specs does get in the way of creating interoperable systems. It is a
                      pity that this disregard for the standards is going to have a knock-on
                      effect for web development clients, where what they will be getting are
                      systems that rely upon code that should not be expected to work in any
                      ECMA 262 compliant environment. They will not know it is happening (why
                      should they as they are not web developers) and the developers foisting
                      such systems upon them will not know that they are doing it (as most, as
                      you say, neither know nor care about ECMA 262, and even could not
                      understand the Prototype.js code if they bothered to look). Yet those
                      clients will have to live with the consequences.
                      then I say the specs lose. Too bad.
                      Web standardisation has been a good thing. We have moved towards, and
                      are now pretty much at, a point where a single, well-defined, scripting
                      language can be used in all scriptable web browsers. Leaving just the
                      inconstancies in the browser's object models to be worked round (while
                      they are gradually reduced by DOM standardisation ). And so it becomes
                      easier for us to do our jobs well.

                      However, it has always been even easier for people to do the web
                      development job badly. Witness the Netscape only, and then (mostly)
                      Microsoft only, web sites. Their creators needed no standards to 'earn'
                      their fees, and their clients probably got what they 'asked' for.

                      Several times over the years I have asked you to state whether you think
                      the client of a professional web developer has a reasonable right to
                      expect that developer to possess the technical skills that they are
                      selling. You have never answered the direct question.

                      Here you are arguing that because a mass or individuals follow a
                      particular course (whether motivated by choice, fashion, ease, perceived
                      familiarity or whatever else) then that course is acceptable (regardless
                      of its consequences).

                      Considering that you publish a javascript 'best practices' page (and
                      frequently refer others to it) isn't that a bit of an inconsistent
                      position? Aren't the majority of the things that would be changed by
                      adopting your 'best practices' precisely the things that are common
                      practice now (or at least in the recent past)?

                      The main reason it is necessary to promote some sort of notion of 'best
                      practices' to replace common practices is that the average technical
                      standard of web developers is abysmal. As javascript developers go you
                      are well above average, but remember that to a large mass of 'web
                      developers' VK (apparently) looks impressive. We all know how very bad
                      VK is in reality, but realistically he probably is, skills-wise,
                      hovering around the average as far as web developers go. The general
                      state of the art really is that bad. The average 'web developer' is so
                      technically unskilled that they could not get work as even the lowliest
                      of programmers in any software house.

                      Given that, appeals to the 'masses' (or worse, the 'lowest common
                      denominator') are not worth considering. In the same way as I have often
                      said that any 'best practice' is not a 'best practice' unless it is
                      accompanied by an explanation that is good enough to convince the reader
                      to follow the practice, a choice of naming conventions should follow
                      from its merits. We have a situation where a naming convention is well
                      known to people who understand javascript, has a context where it can be
                      employed and when used in that context can convey information that is
                      important to individuals needing to work efficiently with the resulting
                      system. That system is not an average web site, and the average 'web
                      developer' is not going to be employed to work on it, and so has no
                      reason to care for that convention.

                      The alternative is not an alternative convention for the meaning of -
                      $ - symbols in javascript (at least nobody has proposed such a
                      convention, here or elsewhere). It is the acceptance of one specific
                      employment of the symbol, negating the convention from the standard but
                      leaving the - $ - symbol to be scattered willy-nilly through javascript
                      Identifiers and having one meaning to one author and another to the
                      next, while improving the readability of nothing through its use.

                      Consider:-

                      alert(this.$.$. id);

                      - (no need to guess who may have written that) Is that a step towards
                      understandable and maintainable javascript code? Is that a price worth
                      paying in order to be able to infer new meaning in - $(x); -
                      specifically?
                      >So when $() is encountered in a code snippet with no other
                      >context, which library are we to assume is in use, and what
                      >purpose is it supposed to fulfil?
                      >
                      We don't know exactly. But I would say almost everyone here
                      knows that $('id') will get a reference to an element with
                      id "id", regardless of which framework has implemented the
                      $() function.
                      Is that really true, when you are arguing about code created by what you
                      are effectively defining as "the people who don't know any better"? Is
                      the result a DOM node with a particular ID attribute, or are we going to
                      get elements with corresponding NAME attributes, a collection of such
                      elements, an augmented Element, etc.? And, much more importantly, what
                      will be the result when the reference fails? Null (as you would always
                      get with getElementById) , undefined, a harmless dummy Element created
                      with JS so that unchecked interaction with it does not throw exceptions,
                      and empty array, and so on? In the context of a question on c.l.js
                      (where questions are usually prompted by things not being quite as they
                      appear at first) that side of the behaviour of some arbitrary - $ -
                      function may be very significant, and only answerable by seeing its
                      definition code (and any dependencies that may have).
                      That's knowledge that's in the world, and
                      that's useful.
                      Believing that you know something that is not the case can be more
                      harmful than knowing that you don't know.

                      Richard.


                      Comment

                      • Matt Kruse

                        #12
                        Re: get an element by id does not work!

                        Richard Cornford wrote:
                        The spec says "The dollar sign is intended for use only in
                        mechanically generated code", which is neither a suggestion nor an
                        order, it is an explanation of why a character that did not need to
                        be included has been included.
                        It was _intended_ for that use. Not an order. So if people want to treat it
                        differently, they may.
                        Why would "Selector" be a name for a wrapper round - getElementById -?
                        Why would - $ - be a better abbreviation than 'S'?
                        I'm not arguing at all that $ was a good choice for function name. Just that
                        it got picked, it became popular, and is now pretty well recognized and
                        used. Prototype, JQuery, Moo, etc all use it.
                        In practice wrapping a - $ - function around - getElementById -
                        (however loosely) is more of a nod toward the Microsoft notion that
                        IDed DOM elements should be made available as properties of the
                        global object (effectively pre-defined global variables).
                        I think it is more tied to resolving, or dereferencing, as you noted above.
                        Which makes it a logical choice, IMO, unconnected to any IE behavior.
                        Several times over the years I have asked you to state whether you
                        think the client of a professional web developer has a reasonable
                        right to expect that developer to possess the technical skills that
                        they are selling. You have never answered the direct question.
                        I believe I have. Of course they have a right to expect that. But in the
                        Real World, that doesn't mean they will get it. And whether they actually
                        get it usually depends on the price they are willing to pay. It's not black
                        and white. Technical skills are a sliding scale, so you cannot say that
                        someone either has Javascript skills or doesn't.

                        There is far more Javascript to be written than exist people with your
                        qualifications to write it. If everyone had to live up to your standards
                        before writing any js code, very little would be written. You may argue that
                        this would be preferrable. I would argue that it would not be.
                        Here you are arguing that because a mass or individuals follow a
                        particular course (whether motivated by choice, fashion, ease,
                        perceived familiarity or whatever else) then that course is
                        acceptable (regardless of its consequences).
                        First, there are no real 'consequences' of using $ in identifiers in
                        javascript. Other than possibly confusing some javascript experts, who
                        probably won't be looking at code using $ anyway.
                        Second, I didn't argue that whatever "the masses" choose is acceptable.
                        Rather, that you must adapt to the Real World, and the masses choose the
                        Real World. If things are moving in a direction that you disagree with, you
                        can either adapt or you can stay firm and become irrelevant. Stick your head
                        in the sand if you wish. The world will move on, despite your protests of
                        its general incompetence.

                        You always focus on yourself - but you're the rare exception. You can code
                        everything yourself. Fantastic. I can't imagine you would use a library,
                        because you could easily write your own code.

                        But when it comes to "the masses" and what people should do who lack the
                        time and skills that you have, your conclusions are very idealistic and not
                        very practical. It's like politicians who talk about lowering taxes, feeding
                        the hungry, saving the environment, ending war, etc - sounds great! But what
                        are you _really_ going to do? Because we all know the idealistic talk is
                        just talk.
                        Considering that you publish a javascript 'best practices' page (and
                        frequently refer others to it) isn't that a bit of an inconsistent
                        position?
                        I don't believe so. You've yet to put forward any convincing argument to me
                        that $() is an unacceptable choice for a function name, other than pointing
                        to specs that say the $ was intended for something else. Well, if everyone
                        stuck to what things were intended for, we certainly wouldn't have any
                        innovation in the world. I need a stronger argument than "that's not what
                        they intended!"
                        to a large mass of 'web developers' VK (apparently) looks impressive.
                        Which is the Real World. Which is why libraries and frameworks must exist.
                        So people like VK cannot be seen as experts, nor their "skills" needed.
                        Because any average Javascript developer can use a solid, robust,
                        cross-browser, standards-compliant library that helps them accomplish their
                        task without having a deep understanding of the inner workings.
                        Consider:-
                        alert(this.$.$. id);
                        That's not absurdly clear to you?! ;)

                        --
                        Matt Kruse




                        Comment

                        • Richard Cornford

                          #13
                          Re: get an element by id does not work!

                          Matt Kruse wrote:
                          Richard Cornford wrote:
                          >The spec says "The dollar sign is intended for use only in
                          >mechanically generated code", which is neither a suggestion
                          >nor an order, it is an explanation of why a character that did
                          >not need to be included has been included.
                          >
                          It was _intended_ for that use. Not an order. So if people want to
                          treat it differently, they may.
                          >
                          >Why would "Selector" be a name for a wrapper round - getElementById
                          >-? Why would - $ - be a better abbreviation than 'S'?
                          >
                          I'm not arguing at all that $ was a good choice for function name.
                          It is not a good choice, it has no inherent meaning and instead relies
                          on an association that is not really equivalent, not universal and is
                          contrarily to an established expectation.
                          Just that it got picked, it became popular, and is now pretty
                          well recognized and used. Prototype, JQuery, Moo, etc all
                          use it.
                          Bad ideas often propagate.

                          It has been observed in the past that individuals who seem most
                          knowledgeable about the application of javascript to browser scripting
                          are not particularly in favour of the notion of general libraries (at
                          least not in the form exemplified by code such as Prototype.js). The
                          people who write these libraries don't (possibly cannot) see why, from
                          their perspective libraries are the obvious approach to code re-use. But
                          having written something that gains the popularity of Prototype.js they
                          are maybe trapped in a vicious circle. They cannot move on and they
                          cannot correct their mistakes. So all they can do is justify them and
                          elaborate them. Prototype.js is way to complex for what it does, way too
                          indirect (very un-javascript) and very inefficient, but those aspects of
                          it are far to fundamental to be fixed. If it were taken as a learning
                          exercise and abandoned now its author's next effort could be orders of
                          magnitude better (the third might even be good, then comes the epiphany
                          when you understand that the general library concept is fundamentally
                          flawed). None of this can happen, people are writing books devoted to
                          Prototype.js and after that what code author is going to be able to come
                          out and say the whole thing was an embarrassing mistake (how many egos
                          are strong enough to do that).

                          I suspect a similar thing happened to you (to some extent). You may
                          recall my saying that when I started in web development I was impressed
                          with you libraries. We are now at a point where you admit to learning
                          from me (even, I think, starting to see merits in my re-usable code
                          design strategies), which means at some point along the path I passed
                          you, which may in turn suggest that you spent rather longer than you
                          should have standing still ("resting on your laurels", as they say).
                          (Direction not withstanding) at least you are now moving forward again.
                          >In practice wrapping a - $ - function around - getElementById -
                          >(however loosely) is more of a nod toward the Microsoft notion that
                          >IDed DOM elements should be made available as properties of the
                          >global object (effectively pre-defined global variables).
                          >
                          I think it is more tied to resolving, or dereferencing, as you
                          noted above. Which makes it a logical choice, IMO, unconnected
                          to any IE behavior.
                          Except with IDed DOM Elements it is not de-referencing (except in a very
                          loose sense), it is looking them up in a tree structure by ID.
                          >Several times over the years I have asked you to state whether
                          >you think the client of a professional web developer has a
                          >reasonable right to expect that developer to possess the
                          >technical skills that they are selling. You have never answered
                          >the direct question.
                          >
                          I believe I have. Of course they have a right to expect that.
                          No, that is the first time you have come out an actually said as much.
                          But in the Real World, that doesn't mean they will get it.
                          Maybe not, but it is the expected relationship between a client and a
                          professional that they employ. And so it defines what is expected of the
                          professional before they label themselves as such.
                          And whether they actually get it usually depends on the price
                          they are willing to pay.
                          I don't think that paying a high price guarantees anything. If someone
                          is brazen enough to be selling skills they do not posses they may well
                          be brazen enough to charge well over the odds for what they are not
                          providing. Indeed, having the balls to charge an excessive fee may be
                          seen as reassuring to the client.
                          It's not black and white. Technical skills are a sliding
                          scale, so you cannot say that someone either has Javascript
                          skills or doesn't.
                          Well, you can say when they don't with certainty. Judging the speculum
                          of those that do is another matter, thought there are stages in
                          understanding that we have all been through and so recognise others who
                          have not passed that point themselves. A trivial example might be
                          someone - eval -ing a constructed dot-notation property accessor. We all
                          know that that is something that you never do once you have got past the
                          basics, so when you see it you know something about the author or code
                          that uses it.
                          There is far more Javascript to be written than exist people
                          with your qualifications to write it. If everyone had to live
                          up to your standards before writing any js code, very little
                          would be written.
                          But the vast majority of javascript code doesn't need someone with my
                          "qualifications " to write it. In the past many people started off with
                          relatively simple form validation and image roll-over effects, neither
                          of which need much understanding of javascript to do well (though they
                          can still be done catastrophicall y badly).
                          You may argue that this would be preferrable. I would argue
                          that it would not be.
                          In what way would it not be preferable for everyone authoring javascript
                          to have a good understanding of the subject and extensive pertinent
                          experience? It may not be practical but it has got to be preferable if
                          it were practical.
                          >Here you are arguing that because a mass or individuals follow a
                          >particular course (whether motivated by choice, fashion, ease,
                          >perceived familiarity or whatever else) then that course is
                          >acceptable (regardless of its consequences).
                          >
                          First, there are no real 'consequences' of using $ in
                          identifiers in javascript.
                          There is considerably expanded potential for people to write more
                          obscure source code and think that they are justified in doing so.
                          Other than possibly confusing some javascript experts, who
                          probably won't be looking at code using $ anyway.
                          Having people not looking at code that has - $ - symbols to the greatest
                          extent possible is a desirable outcome. Reserving the symbol for a
                          general (but relatively uncommon) context where its appearance is a
                          warning that there is another aspect to the code that should not be
                          ignored is the point of following the convention.
                          Second, I didn't argue that whatever "the masses" choose is
                          acceptable. Rather, that you must adapt to the Real World,
                          and the masses choose the Real World.
                          Adapting to a "real world" is no necessarily going along with it. Indeed
                          there have been many things in the "real world" that should never have
                          been gone along with (totalitarian government being an obvious example).
                          If things are moving in a direction that you disagree
                          with, you can either adapt or you can stay firm and
                          become irrelevant.
                          Becoming irrelevant is not necessarily the consequence of not following
                          a crowd.
                          Stick your head in the sand if you wish. The world
                          will move on, despite your protests of its general
                          incompetence.
                          Protestations of general incompetence are not going to change anything
                          (even if they explain some things) but reasoned arguments for a
                          particular position may well influence individuals, and if sufficient
                          individuals are influence then the result may be to change the outcome
                          of things.
                          You always focus on yourself - but you're the rare exception.
                          I don't know about always focusing on myself, but I do have pertinent
                          experience. Inevitably, before I started working in web development
                          there was a time when I knew nothing about the subject, and the earliest
                          javascript I wrote is so bad, looking back on it, that it is
                          embarrassing to think about it now (and it did all of the things that I
                          now recognise as bad, including probably directly costing the people who
                          used it income). That is, I have been as bad a web developer as any (in
                          terms of technical ignorance at least, I have not been as idle,
                          disinterested, self-satisfied, dishonest, etc. as some). That means that
                          I am not necessarily a rare exception, just someone at a point on a path
                          where few have been before but many yet choose to follow.
                          You can code everything yourself. Fantastic. I can't imagine
                          you would use a library, because you could easily write your
                          own code.
                          What is a library? For the last couple of years I have been working on
                          frameworks for web applications. From one point of view that is a
                          library (indeed Yahoo distribute their application framework in the
                          guise of a general-purpose library, though that may just be so they can
                          get it vigorously tested (even debugged) at negligible internal cost).
                          But when it comes to "the masses" and what people should do
                          who lack the time and skills that you have, your conclusions
                          are very idealistic and not very practical.
                          Here you go again. You admit that the client has a reasonable
                          expectation that the professionals they hire should posses the skills
                          pertinent to their profession, but then excuse those 'professionals' for
                          not having the time or inclination to learn those skills.
                          It's like politicians who talk
                          about lowering taxes, feeding the hungry, saving the environment,
                          ending war, etc - sounds great! But what are you _really_ going to
                          do? Because we all know the idealistic talk is just talk.
                          >
                          >Considering that you publish a javascript 'best practices'
                          >page (and frequently refer others to it) isn't that a bit
                          >of an inconsistent position?
                          >
                          I don't believe so. You've yet to put forward any convincing
                          argument to me that $() is an unacceptable choice for a
                          function name,
                          I am yet to convince you, others may see things differently.
                          other than pointing to specs that say the $ was intended
                          for something else.
                          And to point out that the name has no inherent meaning (beyond the
                          convention in the spec and its use as a currency symbol in the wider
                          world), that its associations with the dollar symbol's use in other
                          languages does not really fit with how it is being employed in this
                          context, and that abandoning the convention and allowing it in this
                          context means allowing the use of the dollar symbol in any other
                          contexts, with the consequent general obscuring of javascript source
                          code as individuals adopt their own personal 'conventional' meanings
                          attached to a symbol that adds nothing to Identifier clarity in itself.
                          Well, if everyone stuck to what things were intended for, we
                          certainly wouldn't have any innovation in the world.
                          What "innovation " do you propose could follow from abandoning a common
                          naming convention in a programming language? It is not as if choosing to
                          write clear source code gets in the way of actually doing anything with
                          the language. The computers don't care at all what names we may or may
                          not use as Identifiers, so long as the syntax rules are not broaden.
                          I need a
                          stronger argument than "that's not what they intended!"
                          And I don't (even though other arguments exist). I lose nothing from
                          following the convention from the language specification, and I may gain
                          something (though more likely my employer will see the real benefits).
                          >to a large mass of 'web developers' VK (apparently) looks
                          >impressive.
                          >
                          Which is the Real World. Which is why libraries and frameworks
                          must exist. So people like VK cannot be seen as experts, nor
                          their "skills" needed.
                          VK is about bamboozling people who don't know any better. You don't
                          address that by letting people get away with never learning to know
                          better, quite the reverse.
                          Because any average Javascript developer can
                          use a solid, robust, cross-browser, standards-compliant library
                          that helps them accomplish their task without having a deep
                          understanding of the inner workings.
                          And Prototype.js is not a solid, robust, cross-browser,
                          standards-compliant library (well, I might accept "solid", very solid,
                          one very solid lump of code).
                          >Consider:-
                          >alert(this.$.$ .id);
                          >
                          That's not absurdly clear to you?! ;)
                          It was not even clear to the individual who wrote it. The object
                          referred to by - this - was the same object as was refereed to by the
                          second - $ - and so the whole thing could have been replaced with -
                          alert(this.id); -. If the original property accessor had used meaningful
                          Identifiers, a more context specific equivalent of -
                          this.jsObject.d omElement.id - for example, then it might even have been
                          obvious to its own author that he was going around in pointless circles
                          (and the memory-leaking tight circular reference between a DOM node and
                          JS object may also have been apparent (though at the time VK was
                          swearing that IE's circular reference problem was not real, despite
                          repeatedly being shown otherwise)).

                          So, absurd yes, clear no.

                          Richard.


                          Comment

                          • Matt Kruse

                            #14
                            Re: get an element by id does not work!

                            Richard Cornford wrote:
                            It has been observed in the past that individuals who seem most
                            knowledgeable about the application of javascript to browser scripting
                            are not particularly in favour of the notion of general libraries
                            True in some cases, but not true in many other cases. I'm not sure exactly
                            who you include in the list of "individual s who seem most knowledgeable".
                            Recently I've seen various js "experts" swaying towards accepting libraries,
                            especially jQuery.
                            recall my saying that when I started in web development I was
                            impressed with you libraries. We are now at a point where you admit
                            to learning from me
                            Of course. I learn from many people. I could also offer many criticisms of
                            your code. Especially if you were to actually publish any of it to help
                            improve the knowledge of others.
                            (even, I think, starting to see merits in my
                            re-usable code design strategies)
                            In some of your reusable components? Somewhat. In your general approach? Not
                            at all. I'm still not sold, and suspect I never will be.
                            which means at some point along
                            the path I passed you
                            Is it a race? Is there even just a single road?
                            which may in turn suggest that you spent
                            rather longer than you should have standing still ("resting on your
                            laurels", as they say).
                            If I were the type to be easily offended, I would perhaps be offended by
                            that comment. On the contrary - I have started a family, dealt with some
                            health issues, focused on mastering other technical areas, and spent time
                            pursuing some things unrelated to technology. I've not stood still, but
                            instead moved forward on several of other roads.
                            (Direction not withstanding) at least you are
                            now moving forward again.
                            More like just flushing out my thoughts which were on hold.
                            >There is far more Javascript to be written than exist people
                            >with your qualifications to write it. If everyone had to live
                            >up to your standards before writing any js code, very little
                            >would be written.
                            >...
                            >You may argue that this would be preferrable. I would argue
                            >that it would not be.
                            In what way would it not be preferable for everyone authoring
                            javascript to have a good understanding of the subject and extensive
                            pertinent experience?
                            I meant you would prefer that little code would be written, rather than more
                            code that is merely average.
                            (indeed Yahoo distribute their application framework in the
                            guise of a general-purpose library, though that may just be so they
                            can get it vigorously tested (even debugged) at negligible internal
                            cost).
                            I can't say that this doesn't capture some of my personal motivation as
                            well.
                            Here you go again. You admit that the client has a reasonable
                            expectation that the professionals they hire should posses the skills
                            pertinent to their profession, but then excuse those 'professionals'
                            for not having the time or inclination to learn those skills.
                            The skill required should be to build an interactive web site/app. Whether
                            they write the javascript from scratch or not doesn't matter. If they use a
                            library and get a good result that meets expectations, then good for them.
                            What "innovation " do you propose could follow from abandoning a common
                            naming convention in a programming language?
                            Not from using the $ necessarily, but from accepting the progress made by
                            those libraries and approaches that happen to use the $ function, rather
                            than dismissing them outright.

                            --
                            Matt Kruse




                            Comment

                            • Randy Webb

                              #15
                              Re: get an element by id does not work!

                              Matt Kruse said the following on 1/16/2007 9:09 PM:
                              Richard Cornford wrote:
                              >It has been observed in the past that individuals who seem most
                              >knowledgeabl e about the application of javascript to browser scripting
                              >are not particularly in favour of the notion of general libraries
                              >
                              True in some cases, but not true in many other cases. I'm not sure exactly
                              who you include in the list of "individual s who seem most knowledgeable".
                              Recently I've seen various js "experts" swaying towards accepting libraries,
                              especially jQuery.
                              That list would, inevitably, be limited to the "most knowledgeable" that
                              do not like libraries :)

                              That creates a problem though. The "most knowledgeable" will see the
                              potential benefits to having a basic library.

                              --
                              Randy
                              Chance Favors The Prepared Mind
                              comp.lang.javas cript FAQ - http://jibbering.com/faq/index.html
                              Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/

                              Comment

                              Working...