J van Amerongen J van Amerongen - 21 days ago 4x
Javascript Question

Is there a better (more sensible) way to achieve this same goal?

I have a working solution to a previous problem, but it does not feel like good programmer's habit. Is there a better solution or is this just the way to go?

Here's my HTML:

<li onclick="answer(this)">A</li>
<li onclick="answer(this)">B</li>
<li onclick="answer(this)">C</li>
<li onclick="answer(this)">D</li>

And my JS:

window.answer = function (elm) {

if ($(elm).is(':nth-of-type(1)')) {

alert('elm is 1st of type');

} else if ($(elm).is(':nth-of-type(2)')) {

alert('elm is 2nd of type');

} else if ($(elm).is(':nth-of-type(3)')) {

alert('elm is 3rd of type');

} else if ($(elm).is(':nth-of-type(4)')) {

alert('elm is 4th of type');



What this code does, is it alerts what nth child it is (for the 2nd
it alerts
elm is 2nd of type

In short, is there a better (more logical) way to achieve the same result? And if so, how should I implement that?



Since you're using JQuery, you may find utility to the use of index function :


In your answer function, you can then add a selector for all the li you want to match (if you have multiple unordered lists for example), and then :

var zeroBasedIndex = $("your-li-selector").index(elm);

Keep in mind this returns a zero-based position, feel free to ++ it to find your positions back.

Hope this helps