Add findElement and findAllElments methods to controllers #854
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
findElementandFindAllElementsto the Controller classMotivation
This was motivated by being frustrated by having to use
this.element.querySelectorto get access to elements based on their class or id and also having to prepend.to classes and#to ids. Usingdocument.getelementByIdalso didn't feel right, especially since it wasn't scoped to the root element of the controller.This PR attempts to make the code look much more 'Stimulus' in style when selecting elements
Usage
Given the following HTML:
Find Elements scoped inside the root element by passing the id:
this.findElement("inside")will return<div id="inside" class="busy loading">...</div>this.findElement("outside")will returnundefinedsince it doesn't match any element inside the controllerFind elements using defined classes:
this.getElement(this.activeClass)will return<div class="active">...</div>this.getElement(this.loadingClasses)will return<div class="busy loading">...</div>Find element using a standard query selector:
this.getElement(.active p.intro)will return<p class="intro">...</p>The method looks for items with an id first, then looks to see if any classes have been defined on the controller and last of all falls back to using
this.element.querySelectorthis.findAllElementsworks in the same way, but returns an array of all matching elements. It does not look for elements with an id as there should only be one element with an id.