I’ve been adding quite a bit of javascript to my pages lately, but have learned it all in classic seat-of-the-pants fashion. When I want my page to do something, I google and experiment until I get the result I want.
I frequently have objects in my pages that I want to activate/deactivate, hide, show, etc., but – having missed the rigorous introduction to javascript – I’ve no idea how these things get named. I click on objects with firebug open, expecting to see some fully-qualified name for the object, but get no joy. I just need to be able to do something like form.button.value=”something”, and need to know the name of that object.
Any ideas?
Thanks.
Whilst you are running Javascript code, you have all the local variables in the current scope, so if you had the following code:
… your root object would be myObject, and you refer to descendent objects through the dot notation.
However, thanks to the implementation of the DOM in the browser, you also inherit the
windowobject via thethiskeyword. In fact, you can leave thethiskeyword out for simple situations i.e. when you are not using closures. Therefore, you can access Javascript functions at the top level by just using the function name.If you want to access specific elements, like it sounds like you are wanting, you need to learn the DOM, and not use the syntax that you were suggesting (that sounds like 1990s Javascript). The root element you need to know is the
HTMLDocumentobject, accessed via thedocumentproperty. You can discover elements with specificId(notName) attributes by using thegetElementByIdmethod of the document element. Of course, it helps if you’ve given your element an unique Id from the start. You can also recursively use thechildNodescollection to iterate manually through elements until you find what you want. Alternatively, if you really can’t supply an Id, you could also use thegetElementsByTagNamemethod, which is attached to every element in the DOM.Example: