I’m looking for some advice on a making my jQuery selectors more configurable. For example, given the following HTML generated by PHP:
<ul id="my-list">
<li>first</li>
<li>second</li>
</ul>
And a bit of jQuery:
$(function() {
$(document).on("click", "#my-list li", function() {
alert("You clicked " + $(this).text());
});
});
So far so good, but then one day the designer comes along and renames the id “my-list” to “list-of-numbers”, and the javascript stops working. Currently the solution is remembering to grep through the code for any references to “my-list”, but that’s very faulty. Is there a jQuery design pattern for making the selectors configurable?
This can be called ‘selector selection.’ You can define a set of variables that have the selectors in them as a solution:
Then you can simply do an object lookup to get the selector:
This has the advantage of being readable and dynamic; however, in your example scenario where someone changes the
ID, this would not be very helpful unless it’s explicitly noted somewhere in your code that changes are necessary.You might want to consider doing some delegation and using custom data attributes to define roles.