If ID contains Javascript

100 views Asked by At

I have following JS

    var slider = new Slider("#testslider", {
        tooltip: 'always'
    });

To style my bootstrap slider by ID. I want to style every slider in that area so I tried to put them all in one DIV like:

<div id="testslider">
//all sliders
</div>

That will only style the first slider.

I tried [id^="testslider"] and named every slider in this scheme: testslider1, testslider2 etc.

But that will only style the first slider. Now with document.querySelectorAll([id^="testslider"]); I could select all IDs but I can't figure out how to put that into

var slider = new Slider("#testslider", {
    tooltip: 'always'
});
1

There are 1 answers

4
Louys Patrice Bessette On BEST ANSWER

Now with document.querySelectorAll([id^="testslider"]); I could select all IDs but I can't figure out how to put that into

var slider = new Slider("#testslider", {
  tooltip: 'always'
});

I suppose you absolutely need the id to instanciate the tooltip plugin...
Use a loop to go through each elements, get it's specific id to instancitate the slider:

const allSliders = Array.from(document.querySelectorAll('[id^="testslider"]'));
console.log("allSliders length:", allSliders.length)

allSliders.forEach((element) => {
  console.log("id for tooltip:", "#"+element.id)  // To check if the right ids are used
  new Slider("#"+element.id, {  // The specific id is used here
    tooltip: 'always'
  });
})