2

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.

4

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?)

  • I like this approach. FWIW - when I try var jquerySubComponents = $(subComponents); - I get the error Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '[object NodeList]' is not a valid selector. – mralexlau Aug 4 '15 at 16:59
  • What version of jQuery are you using? This worked for me against 1.11 var list = document.querySelectorAll("DIV"); alert($(list)); – Kris Gray Aug 4 '15 at 17:07
  • 1
    weird, I was using 2.1.4 before but it seems to work in 1.11.3 – mralexlau Aug 4 '15 at 22:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.