How to Select a Range of Elements using jQuery ?
Given an HTML document with a range of similar elements and the task is to select a range of those elements with the help of JavaScript. There are two approaches that are discussed below with an example.
Approach 1: First, select all elements of class = ‘child’ by jQuery selector then use slice() method to select a range of elements continuously. The background color of the elements has been changed to see the effect.
- Example:
<!DOCTYPE HTML><html><head><title>How to select a range of elements in JQuery</title><scriptsrc=</script><style>h1 {color: green;}.geeks {color: green;font-size: 24px;font-weight: bold;}</style></head><body><center><h1>GeeksforGeeks</h1><b>Click on button to select a rangeof elements</b><divclass="outer"><divclass="child">Child 1</div><divclass="child">Child 2</div><divclass="child">Child 3</div><divclass="child">Child 4</div></div><br><buttononClick="gfg()">click here</button><pid="geeks"></p></center><script>var down = document.getElementById('geeks');// Defining childsvar arr = [0, 2, 3];function gfg() {var $el = $(".outer .child");for (var i = 0; i <arr.length; i++) {$el.slice(arr[i], arr[i] + 1).css("color", "red");}down.innerHTML="Range of elements selected";}</script></body></html> - Output:

Approach 2: First select all elements of class = ‘child’ by jQuery selector. There is an array which contains the indexes of the elements to be selected. We are traversing the array and using slice() method to select the particular element of that index. The background color of the elements has been changed to see the effect.
- Example:
<!DOCTYPE HTML><html><head><title>How to select a range of elements in JQuery</title><scriptsrc=</script><style>h1 {color: green;}.geeks {color: green;font-size: 24px;font-weight: bold;}</style></head><body><center><h1>GeeksforGeeks</h1><b>Click on button to select a rangeof elements</b><divclass="outer"><divclass="child">Child 1</div><divclass="child">Child 2</div><divclass="child">Child 3</div><divclass="child">Child 4</div></div><br><buttononClick="gfg()">click here</button><pid="geeks"></p></center><script>var down = document.getElementById('geeks');// Defining childsvar arr = [0, 2, 3];function gfg() {var $el = $(".outer .child");for(var i=0; i<arr.length; i++) {$el.slice(arr[i], arr[i]+1).css("color", "red");}down.innerHTML="Range of elements selected";}</script></body></html> - Output:



