JQuery collation selector ("id" vs. "class")?

I have several lists that are sorted, and I can drag and drop items into each list.

The setup looks something like this:

<ul id="sortable1" class="connectedSortable"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> <ul id="sortable2" class="connectedSortable"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> 

JavaScript is simple and looks like this:

(following examples from jQuery)

 <script> $(function() { $( "#sortable1, #sortable2" ).sortable({ connectWith: ".connectedSortable" }).disableSelection(); }); </script> 

so far so good ...

Question:

For jQuery selector, can you use ul class instead of two list ids?

Sort of:

 <script> $(function() { $( ".connectedSortable" ).sortable({ connectWith: ".connectedSortable" }).disableSelection(); }); </script> 

Is it correct?

I tried this and it works ...

... but I wonder why the jQuery website provides an example with both list identifiers and a selector, not just a class name? Can I run into compatibility issues if I use the class as a selector?

The advantage of using a class name as a selector would be that I don't need to know the list identifiers in advance and theoretically create new lists on the fly?

What would be the best practice and kind of โ€œmistakeโ€?

Thanks a lot!

+6
source share
1 answer

The class selection is fine, and your script is correct.

I have never encountered compatibility issues when selecting items by their class.

Using class names, it makes sense not to specify the identifiers of all elements that must match. Its maladaptation is the ability to map more elements than you intend if the class was misused in other elements.

When specifying elements by identifier, you are sure that you have selected only the elements you have selected. Therefore, this can be useful when you know exactly which DOM elements you want to map, and you know their identifiers; this, as you noticed, may not be possible if you create the elements on the fly.

I think in your case the best practice would be to use class names. Do not use the class name that you map to CSS; if he is responsible for formatting, you (or other people in your team) can forget about the behavioral changes he makes and use them on other, unrelated elements, just for formatting. This can lead to errors. Itโ€™s better to have separate behavioral and presentation classes, use presentation classes in CSS and behavior classes to select elements in jQuery.

+2
source

Source: https://habr.com/ru/post/900916/


All Articles