2

Now I am using "Perfect Scroller" which is a custom scroll bar plugin.

I followed the Document to setup.Here

I use code like below and every was good.

var container = document.getElementById('container');
Ps.initialize(container);

However, I want to use it by "ClassName" not by "ID" because there are lots of areas.

I know I can use

var container = document.getElementsByClassName('selected_area')[0];

But this is only one element.

My question is how to do it by ClassName?

3 Answers 3

5

You can do in a loop:

 var container = document.getElementsByClassName('selected_area');
 for(var i in container) {
      Ps.initialize(container[i]);
 }

This iterates all containers and initialize it independently.

Sign up to request clarification or add additional context in comments.

2 Comments

No, its a key which happens to be the index in this special case. And because of this you should not use for ... in ... as it is meant to iterate over the enumerable keys of an object. Use a for loop instead.
Interesting reading: etnassoft.com/2011/09/21/… for-in is better if you don't use it in a customized array, but in a structure of things like getElementByClassName returns is totally accepted and good practice. You doesn't need iterate in numeric order this initialization. All of you goes post by post with a new mantra Don't use for-in, and it is not correct. Please, understand how for-in works and then use when you need it.
1
var container = document.getElementsByClassName('selected_area');

for(var i = 0; i < container.size; i++){
     Ps.initialize(container[i]);
}

Although I haven't had a look at this plugin you are using, so I don't know if it should be initialised more than once. Hope this helps

Comments

0

you can also use:

var container = document.querySelectorAll('.selected_area');

furthermore you can transform it to an array(it's only necessary if you want to use standard array methods)

 var contArr = [].slice.call(container)

in this case you can then use it with forEach

 contArr.forEach(function(x){Ps.initialize(x)}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.