Page 1 of 3 123 LastLast
Results 1 to 10 of 29

Thread: Replacing document.getElement

  1. #1
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default Replacing document.getElement

    Ok, so I had an idea....

    Firstly, I don't know jack about DOM, but secondly, I like the methods of Jquery, and the $('#whatever').html programming.

    But here is the deal.

    Code:
    function showme(value)
    {
    document.getElementById(value) = document.form1.value;
    alert(document.getElementById(value).innerHTML);
    }
    Is something like this possible? doesn't work with that, but the concept of replacing "document.getElementById" with a valid DOM method of getting an element would enable people to use "document.getElementById" without it farking up.

    If a library could be made to convert the "document.getElementById" method to the proper DOM method, it would be convenient for old scripts working valid.

    - Best

    - Ben
    document.write is document.wrong

  2. #2
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    First off, the keyword value is semi-reserved, especially as concerns form inputs and textareas, so is a poor choice here.

    Second, if you want backward compatibility and are dealing with forms anyway, just use the document.forms methods.

    Third, in jQuery the $('#someId') function will not work if the browser doesn't support the document.getElementById() method. It is not a backward compatibility method, it is a function to extend element objects in modern browsers that already support the document.getElementById() method.

    If you want a function that would be as equivalent as possible to document.getElementById() and that would be backward compatible and still allow the use of document.getElementById() as the name of the function/method, you can do:

    Code:
    if(!document.getElementById)
     document.getElementById = function(id){
      return document.layers? document.layers[id] : document.all[id];
     }
    Or, if you want to make a shortcut that is backward compatible and always use that:

    Code:
     function myGet(id){
      return document.layers? document.layers[id] : document.getElementById? document.getElementById(id) : document.all[id];
     }
    If you want both a shortcut, and to be able to use document.getElementById() in your code as well and have it be backward compatible:

    Code:
     function myGet(id){
      if(myGet.backward)
       return document.layers? document.layers[id] : document.all[id];
      return document.getElementById(id);
     }
     myGet.backward = !document.getElementById;
     if(myGet.backward)
      document.getElementById = function(id){return myGet(id);};
    But these aren't really all that useful. One would need a version 4 browser to not have document.getElementById() support (NS 4, or IE 4).

    Those browsers will have difficulty rendering valid HTML, let alone running any modern javascript, regardless of whether or not something like this is used.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  3. #3
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    That's not good, because it will also return name-indexed elements (which may be collections).

    You should check:
    Code:
    if (!document.getElementById)
      document.getElementById = (function(coll) {
        function getElementById(id) {
          var els = coll[id];
    
          // No such element.
          if (!els)
            return null;
    
          // Element was the desired element.
          if (els.id === coll.id)
            return els;
    
          // Element is presumably a NodeList (if it isn't, --i >= 0 will
          //   fail).
          // Grab an element that looks right (it might not be what's
          //   intended if there's more than one element with the same
          //   ID, but that's invalid anyway)
          for (var i = els.length; --i >= 0; )
            if (els[i].id === id)
              return els[i];
    
          // Move along, boys, nothing to see here.
          return null;
        }
    
        return getElementById;
      })(document.layers || document.all);
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  4. #4
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Quote Originally Posted by Twey View Post
    That's not good, because it will also return name-indexed elements (which may be collections).
    Correct, but a fine point. If the HTML that the code is to run against is well organized, it will be fine. However, none of this is terribly useful, as already mentioned.

    The fact is that the HTML used with older methods, in order for it to be accessible in those browsers must be of a special breed, a subset of valid modern code, with perhaps some invalid but error correctable stuff thrown in for NS 4, or even IE 4. If one is to go to all that trouble, one could as easily also make sure one didn't create named elements (or whatever) in conflict with elements of a given id.

    And as I mentioned before, the javascript itself would be severely limited. Or (to elaborate) at least the branching of it would have to go to dumbed down versions for version 4 browsers. In the latter case, great care often must be exercised in these branchings, as even code not meant for and effectively branched away from in version 4 browsers via normal branching procedures can still cause version 4 browsers to barf simply by virtue of appearing during the first pass of the script parser.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  5. #5
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Yes, of course it's not really worth supporting browsers that old any more.

    I feel the original poster was missing something, though — document.getElementById() is the 'proper DOM method'. The problem is that older browsers don't always support newer standards like DOM, but the ones that don't even have getElementById() support really are very broken nowadays.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  6. #6
    Join Date
    Sep 2008
    Posts
    119
    Thanks
    13
    Thanked 0 Times in 0 Posts

    Default

    Quote Originally Posted by Twey View Post
    Yes, of course it's not really worth supporting browsers that old any more.

    I feel the original poster was missing something, though — document.getElementById() is the 'proper DOM method'. The problem is that older browsers don't always support newer standards like DOM, but the ones that don't even have getElementById() support really are very broken nowadays.

    Thankx for clearing that up Twey.

    I think what happened was a misunderstanding at one point. Most of my scripting would use "<a onclick="function(this.id);">test</a>", instead of attaching the function to the a tag prior (which I learned is actually alot more organized.... no more "tag hunting"). When I did this, my function also had "document.getElementById()", and someone had mentioned that my method was improper usage of the DOM.

    Instead of knowing about pre-tagging elements, I thought that comment meant my "document.getelementbyid" method, since I was aware of doc.form methods and some others, it didn't click, and I thought document.getelementbyid itself was improper.

    However, with the ability to pre-tag elements with functions, I am wondering if there is a simple way to avoid the onclick="function(value);" altogether.

    I think if I used

    Code:
    <div id="test" name="test">blah!</div>
    <script type="text/javascript">
    $ = document.getElementById;
    var alrtdata = "this is my alert";
    var htmldata = "this is my innerhtml data";
    function alrt()
    {alert(alrtdata);}
    function inhtml()
    {$("test").innerHTML = htmldata;}
    $("test").attachEvent("onclick", alrt);
    $("test").attachEvent("onmouseover", inhtml);
    </script>
    It would be a *better* approach than tagging the element, correct?
    Last edited by Falkon303; 02-21-2009 at 07:39 PM.
    document.write is document.wrong

  7. #7
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Browsers will not allow you to farm out document.getElementById like that:

    Code:
    $ = document.getElementById;
    If you are going to use it, just use it. The $ really shouldn't be used in javascript, the fact that jQuery and other libraries do so doesn't make it right.

    There are various ways to get the element clicked on when you've attached/added the event.

    As long as there is no nesting of elements, this works well:

    Code:
    function alertText(e){
     e = e || window.event;
     var t = e.target || e.srcElement;
     alert(t.firstChild.nodeValue);
    }
    A working demo:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <script type="text/javascript">
    function alertText(e){
     e = e || window.event;
     var t = e.target || e.srcElement;
     alert(t.firstChild.nodeValue);
     if(e.preventDefault) e.preventDefault();
     return false;
    }
    
    function myInit(){
     var a = document.getElementById('test');
     if (window.addEventListener)
      a.addEventListener('click', alertText, false);
     else if (window.attachEvent)
      a.attachEvent('onclick', alertText);
    }
    
    if (window.addEventListener)
     window.addEventListener('load', myInit, false);
    else if (window.attachEvent)
     window.attachEvent('onload', myInit);
    </script>
    </head>
    <body>
    <a href="#" id="test">What's This?</a>
    </body>
    </html>
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  8. #8
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    $("test").attachEvent("onclick", alrt);
    $("test").attachEvent("onmouseover", inhtml);
    One of the hazards of giving a function like that such a short name is that you start to feel like you're accessing a variable or something. You aren't: retrieving elements like that is expensive, and should always be cached. A long name helps you remember to do that.

    There's nothing wrong with attaching little bits of JS in your document. These hooks are often much more elegant than the equivalents, and the browser can always ignore them if it doesn't want to work with your script.

    While document.getElementById() is perfectly valid DOM, innerHTML is not part of any standard, and should be avoided wherever possible (and fallback provided when not). Treating code as strings is rarely a good idea.

    John: Why did you choose Transitional and Western-1 over Strict and UTF-8? Nowadays there shouldn't be a reason to use either; they have both been thoroughly relegated to the realms of legacy.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  9. #9
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    30,495
    Thanks
    82
    Thanked 3,449 Times in 3,410 Posts
    Blog Entries
    12

    Default

    Quote Originally Posted by Twey View Post
    John: Why did you choose Transitional and Western-1 over Strict and UTF-8? Nowadays there shouldn't be a reason to use either; they have both been thoroughly relegated to the realms of legacy.
    I use HTML 4.01 Transitional for all of my impromptu projects/demos. Things like this. You will notice:

    Code:
    <body>
    <a href="#" id="test">What's This?</a>
    </body>
    Definitely invalid for HTML 4.01 Strict. I do validate strict for anything I work on for any length of time though, that is if it is/can be supported under that DTD.

    UTF-8 versus iso-8859-1? More just a habit. I'm open to persuasion here. One thing I have noticed though (at least I think this is true) - certain text characters are not supported in UTF-8. Most importantly for me, the © char. I like my on page script comments to sport it where warranted/merited. And, as far as I know, UTF-8 turns it into a 'garbage' (varies, in Fx here it's �) char. I know I can use (c), but I just like ©. Does the charset matter all that much? Isn't that one of those 'at the discretion of the designer' sort of things? I mean, as long as the content is valid in the charset, what's the problem? Other folks need to (well actually not need, but it can be so much more convenient) use other charsets for various languages, is that also wrong in your opinion?
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  10. #10
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Definitely invalid for HTML 4.01 Strict.
    For Transitional too. It's obviously a code fragment, and the reader can be expected to understand as much. They might be newbies, but they're not stupid If you're talking about nesting the <a> directly within the <body>, then while that's true, you should really consider just making the code correct instead. Transitional should not be used for new pages, and I don't think we should be encouraging the habit. It's not difficult to write valid code once you get used to it.
    One thing I have noticed though (at least I think this is true) - certain text characters are not supported in UTF-8. Most importantly for me, the © char.
    UTF-8 is a Unicode encoding. It can represent most of Unicode, which, in practice, means every character you'll ever need (there are some really obscure ones in higher realms of Unicode that it can't support; for these you should use one of the larger Unicode encodings such as UTF-32, but like I say, you'll almost certainly never need them). It certainly has a © character. This is in contrast to Western-1, which supports only a very limited set of characters — Unicode contains a vast superset of the characters of Western-1. For Western (mostly ASCII) text, your default encoding should be UTF-8, which is ASCII-compatible and capable of representing ASCII characters in one byte. The only time you would want to use another encoding is for backwards compatibility with some old (non-Unicode-capable) software, or when encoding a lot of text with a high ratio of characters with high Unicode codepoints, such as Chinese text: in order to represent ASCII characters in one byte, UTF-8 requires three bytes per Han character, whereas UTF-16 requires two bytes for any character.
    And, as far as I know, UTF-8 turns it into a 'garbage' (varies, in Fx here it's �) char.
    This sounds like either your editor is encoding it incorrectly or your server is telling the browser that it ought to be in another charset. Remember that a server header is the preferred method of setting an encoding, and (as with any server header) will override the equivalent <meta> tag if found in the document. The <meta> you've used here should be useful only in case the user decides to save a local copy of the page, in which case server headers will obviously be unavailable.
    Other folks need to (well actually not need, but it can be so much more convenient) use other charsets for various languages, is that also wrong in your opinion?
    Legacy software notwithstanding, they will need to use a charset other than Western-1, which can only represent the Latin alphabet and variations on it, but UTF-8 should suffice for pretty much anyone unless they speak Martian. The only consideration is efficiency: as I said above, in certain cases UTF-16 may be more efficient. Either way, a Unicode encoding is the way to go.
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •