Search code examples
javascriptjquerypolymerweb-component

jQuery selection in polymer webcomponent


Well, out of the box, jQuery does not have support for selecting nodes inside webcomponent(s). (probably because document.querySelector() does not work for shadow DOM (nor it should, by definition)).

Our previous codebase was somewhat dependent on jQuery and many of the devs do not want to let go of the simplicity of $(...) selection. So, I wrapped up this quick and dirty trick.

window.$$ = function (that, selector) {
    return $(that.shadowRoot.querySelectorAll(selector));
}

Usage (inside a lifetime callback or whenever the host node can be accessed):

jqel = $$(this, '.myClass'); // this has reference to the host

The question is, is there a better way to go about this?


Solution

  • i have created a jquery-polymer plugin that has a lot of functions that may help you dealing with polymer shadow dom

    https://github.com/digital-flowers/jquery-polymer

    to select any element inside a polymer element lets say

    <my-button id='button1'></my-button>
    

    first you need to get the button shadow root using

    $("#button1").getShadowRoot() 
    

    or

    $("#button1").shadow()
    

    this will return the button shadow root as jquery object then you can select anything inside it for example

    $("#button1").shadow().find("ul > li:first")
    

    cheers ;)