locked
How come there are no document.getElementByID instances in the "Get started with data" tutorial?

    Question

  • For instance, there is this piece of code:

    buttonSave.addEventListener("click", function () {
                    insertTodoItem({
                        text: textInput.value,
                        complete: false
                    });
                });

    Now, buttonSave is also the ID of a button, but I'm wondering why the code could already use it instantly, without any preceding variable declaration.


    Saturday, November 9, 2013 3:59 PM

Answers

  • The app host automatically creates a variable in the global namespace for any element with an id attribute, with the variable matching the id. So technically, you can get away without using document.getElementById for anything in your markup with an id. Personally, though, I dislike taking advantage of this feature precisely because it leads to the same question you're asking, and you cannot find where the variable is defined in the code. Calling getElementById is very fast in any case, so it's much clearer in the code to be explicit.

    Kraig

    Author, Programming Windows 8 Apps with HTML, CSS, and JavaScript, a free ebook from Microsoft Press

    Also see second edition preview


    Monday, November 11, 2013 4:42 PM

All replies

  • Hi Jd Dantes,

    Thank you for reporting this to use, it seems without the document.getElementByID for a object would confusing the reader.

    Could you provide us the link of the "Get started with data" tutorial? If the issue really exist, I will contact the right person to see if we can provide a more helpful tutorial.

    Thanks for supporting the Store App dev forum.

    Best Regards,

    --James


    <THE CONTENT IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, WHETHER EXPRESS OR IMPLIED>
    Thanks
    MSDN Community Support

    Please remember to "Mark as Answer" the responses that resolved your issue. It is a common way to recognize those who have helped you, and makes it easier for other visitors to find the resolution later.

    Monday, November 11, 2013 1:39 AM
    Moderator
  • The app host automatically creates a variable in the global namespace for any element with an id attribute, with the variable matching the id. So technically, you can get away without using document.getElementById for anything in your markup with an id. Personally, though, I dislike taking advantage of this feature precisely because it leads to the same question you're asking, and you cannot find where the variable is defined in the code. Calling getElementById is very fast in any case, so it's much clearer in the code to be explicit.

    Kraig

    Author, Programming Windows 8 Apps with HTML, CSS, and JavaScript, a free ebook from Microsoft Press

    Also see second edition preview


    Monday, November 11, 2013 4:42 PM