Like jQuery with its $
function, Polymer also has a very handy way to locate nodes in the DOM of the page. This recipe shows you how to use it. You can find the code in the project find_nodes
.
webindex.html
, where a component with the name find-nodes
is imported through the following line:<link rel="import"href="find_nodes.html">
From this, we know that the component is defined in find_nodes.html
, and the code behind it is in a file named find_nodes.dart
. For a discussion of the other tags, refer to the first recipe.
find-nodes
is defined in find_nodes.dart
:import'dart.html'; import'package:polymer/polymer.dart'; @CustomTag('find-nodes') classFindnodes extends PolymerElement { Findnodes.created() : super.created(); btnclick(MouseEvent e, var detail, Node target) { // making the paragraph visible: $['show'].style ..display = 'inline' ..color = 'red'; // changing the text inside the div: Element insideDiv = $['findme']; insideDiv.text = 'I was looked up by $ and changed!'; } }
find_nodes.html
:<link rel="import"href="packages/polymer/polymer.html"> <polymer-element name="find-nodes"> <template> <div class="auto-style1"> <div id="findme">Hello from inside a div</div> <button on-click="{{btnclick}}">Click to find</button> </div> <p id="show" style="display:none">==> I was found by $ and became visible! </p> </template> <script type="application/dart"src="find_nodes.dart"></script> </polymer-element>
The following screenshot shows you what you will see when you run the app:
In step 2, we see that the paragraph with ID show
is shown when the button is clicked because of the line $['show'].style.display = 'inline';
in the event handler. Likewise, an element reference to <div>
with the ID findme
is found with $['findme']
. The code uses automatic node finding, a Polymer feature, to get a reference to each HTML element. Every node in a custom element (so inside the shadow DOM!) that is tagged with an id
attribute can be referenced by its ID using the syntax $['ID']
.