Search code examples
javascriptjquerypolymer

How to prevent jquery global selector selects something outside of the Polymer element


I am trying to use a jquery based library within my Polymer element <my-element>. But once there are more than one of such <my-element> in one page, the library only selects first one because it is selecting an id that is unique within one instance of <my-element> but repeated in multiple ones. How to give jquery selector a domain so that it will only select within it?


Solution

  • It doesn't work because jQuery's id selector is optimized to fetch just the first one:

    Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.


    You can pass jQuery selector's context as its second parameter (interestingly, if you pass multiple contexts, it selectes multiples ids):

    // Initialize selected domains
    $('#init-id', '.first-domain, .second-domain').initializeLibrary();
    
    // Initialize all id in DOM
    $('#init-id', '*').initializeLibrary();
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="first-domain">
      <img id="init-id" />
    </div>
    <div class="second-domain">
      <img id="init-id" />
    </div>
    <div class="do-not-initialize-domain">
      <img id="init-id" />
    </div>


    Alternatively, your component could initialize itself with Polymer.dom(this.root):

    <dom-module id="my-component">
    
      <template>
        My component - yay!
      </template>
    
      <script>
    
        Polymer({
    
          is: 'my-component',
    
          ready: function() {
            $(Polymer.dom(this.root)).initializeLibrary();
          }
    
        });
    
      </script>
    
    </dom-module>