[SalesForce] Scoping jQuery Selectors Within Lightning Components

It seems to me that if you use any jQuery selectors within a lightning component, it would be a best practice to scope them to the current component only. Is there a best practice/recommended way of doing this?

For example, in a JS-controller of a lightning component, I could write:

$('.some-selector')

But that will effect all elements on the page, rather than just the ones within my lightning component. A potential solution would be to add a uid to the top level dom element for the component and say something like:

$('.my-component-uid .some-selector')

Which will work, but I'm not sure if it's the best/recommended way of solving this problem.

Best Answer

So internally to Salesforce we tell people to not use jQuery, just go straight to the DOM.

var subComponents = component.getElement().querySelectorAll(".some-selector");

If you wanted to use jQuery with that you could

var jquerySubComponents = $(subComponents);

If you didn't want to (or couldn't) do that, then you could assume the className of your component based on convention.

<stackexchange:example/>
var myCmp = $(".stackexchangeExample");

But this will get you all the instances of the component on the page, which could be more than you expected. (Someone else using it in another part of the page?)