Search code examples
javascriptgetattributebootstrap-slider

How to capture value of an attribute in JavaScript not jQuery


I want to capture the value of an attribute on an tag using JavaScript. I am not yet successful doing so.

Here's my HTML markup:

<html>
<head>
...
  <!-- bootstrap-slider Plugin -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/bootstrap-slider.min.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/css/bootstrap-slider.min.css" rel="stylesheet">    
...
</head>
<body>
...
    <div class="form-group">
      <label class="col-md-4 control-label" for="language_spanish">Spanish</label>
      <div class="col-md-6">
        <input id="language_spanish" type="text" data-provide="slider"
          data-slider-ticks="[0,1,2]"
          data-slider-min="0"
          data-slider-max="2"
          data-slider-step="1"
          data-slider-value="0"
          data-slider-tooltip="show"
          data-identifier="this is what I want to capture"
        />
      </div>
    </div>
...
</body>
</html>

Here is my javascript:

var spanish = new Slider( '#language_spanish', { formatter } );
spanish.on( 'slideStop', function( value ) {
  alert( value ); // this works perfectly!
  alert( this.getAttribute( 'data-identifier' ) ); // does not work
  alert( spanish.getAttribute( 'data-identifier' ) ); // does not work either
  alert( spanish.attr( 'data-identifier' ) ); // does not work as well
});

Is it possible?

FYI jQuery does not work with bootstrap-slider. Tried and tried and tried and I keep hitting brick walls. JavaScript has been the only way I can use this plugin to retrieve values and attributes.

Amended to include source of plugin:

https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/bootstrap-slider.min.js

https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/css/bootstrap-slider.min.css


Solution

  • You can use spanish.element object which returns the reference of underlying DOM element, then getAttribute() method can be used.

    var spanish = new Slider('#language_spanish');
    console.log(spanish.element.getAttribute( 'data-identifier'))
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/css/bootstrap-slider.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/9.7.2/bootstrap-slider.js"></script>
    
    
    <div class="form-group">
      <label class="col-md-4 control-label" for="language_spanish">Spanish</label>
      <div class="col-md-6">
        <input id="language_spanish" type="text" data-provide="slider" data-slider-ticks="[0,1,2]" data-slider-min="0" data-slider-max="2" data-slider-step="1" data-slider-value="0" data-slider-tooltip="show" data-identifier="this is what I want to capture" />
      </div>
    </div>