0

At first i only want to know if this:

document.getElementsByClassName("main-content_datafield").style.width= this.value;

is valid to use. If it is i would made a mistake. I want to create a rangeslider that controlls the size of some objects. For this i used javascript to get the value of the slider and added the code from before. So finaly it looks like this:

http://jsfiddle.net/oqh16n2u/1/

So what did i do wrong here?

thank you!

dsfsdf
  • 5
  • 1
  • possible duplicate of [Change the style of an entire CSS class using javascript](http://stackoverflow.com/questions/9153718/change-the-style-of-an-entire-css-class-using-javascript) – Rino Raj Aug 23 '15 at 17:32
  • 2
    `getElementsByClassName` returns a DOMElement collection (multiple elements, kind of like an Array). To be able to change properties on them, you need to iterate over them, and use `[0]`, `[1]`, etc. – blex Aug 23 '15 at 17:32
  • Also, you need to add +'px' to your assignment to make it work... – sinisake Aug 23 '15 at 17:39

3 Answers3

1

Try utilizing for loop to iterate HTMLCollection returned by .getElementsByClassName() , adding "px" after this.value to set width of element

var scale_range = document.getElementById('scale_range');
demo = document.getElementById("demo");

scale_range.onchange = function () {
    demo.innerHTML = this.value;

    var elems = document.getElementsByClassName("main-content_datafield");
    for (var i = 0; i < elems.length; i++) {
        elems[i].style.width = this.value + "px";
    }
}

jsfiddle http://jsfiddle.net/oqh16n2u/5/

guest271314
  • 1
  • 15
  • 104
  • 177
0

As you are already using jQuery, U can get the desired effect using css() method in jQuery.

scale_range.onchange = function() {
    demo.innerHTML = this.value;
    $('.main-content_datafield').css('width',this.value+'px');
}

Working fiddle: http://jsfiddle.net/MasoomS/oqh16n2u/4/

Masoom
  • 743
  • 1
  • 5
  • 15
0

You are almost there. Here are some issues with your code:

  1. document.getElementsByClassName("main-content_datafield") returns an an array-like object and not a DOM Element object. So, you'll have to iterate on that array.
  2. width property takes in the unit as well.

So you are better off with something like:

document.getElementsByClassName("main-content_datafield")[i].style.width = this.value + 'px'; in a loop.

Atishay Jain
  • 63
  • 1
  • 6
  • 1
    _"document.getElementsByClassName("main-content_datafield") returns an array"_ See https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName – guest271314 Aug 23 '15 at 18:02
  • @guest271314 - Thanks for pointing that out. I'll make an edit and add your reference :) – Atishay Jain Aug 23 '15 at 18:12