Haradzieniec
Haradzieniec

Reputation: 9340

using javascript code not for id, but for classes

I have a javascript function MyFunc() that does what it has to do with id="item_for_MyFunc". In the function there is a

var elem = document.getElementById("item_for_MyFunc");

and html body has:

<body onload="MyFunc()">
<p id="item_for_MyFunc">

Everything works, but I want to use this function for several items on the page. That's why I should use <p class="item_for_MyFunc"> several times on the page to be processed by this function, so using id is not a solution.

What changes in the function should be done so it could be changed for class="item_for_MyFunc"?

Upvotes: 2

Views: 107

Answers (3)

Ashwin Prabhu
Ashwin Prabhu

Reputation: 7624

document.getElementsByClassName

would return an array of all HTML elements using the class name. Iterate over the results and you are set. Supported in all browsers except IE <= 8, FF < 3. Works just like document.querySelectorAll (works in IE >= 7, FF >=3.5)

Refer: http://quirksmode.org/dom/w3c_core.html#gettingelements for compatibility chart.

Upvotes: 2

Geuis
Geuis

Reputation: 42267

So what you're doing there is pretty simple. Let me give you a slightly more robust version:

document.addEventListener('load', function(){

    var elements = document.querySelectorAll('.myClassName');
    for(var i=0, len=elements.length; i<len; i++){
        MyFunc.call( elements[i] );
    }

}, false);

So old versions of IE, 6 and 7 to be specific, don't have querySelectorAll. I'm assuming you aren't worried about them. If you are, there's other ways to do this and I can show you how if you need.

Basically we're giving all of your elements a class of 'myClassName', and querySelectorAll finds all of them and returns an array of DOM elements.

We then iterate through the list, and execute MyFunc on each of those elements.

Edit So one key principal of writing good javascript is to separate the js code from your html markup as much as possible. You should almost never use inline event handlers like onload="myFunc" anymore. Use event handlers written in the js itself.

If you have the option, you should use the jQuery library. It makes a lot of this stuff incredibly easy, has great support for very old browsers, and is used on hundreds of thousands of websites.

Upvotes: 4

Stu
Stu

Reputation: 4150

You could try:

var elems = document.getElementsByClassName('myClass');

I've not used that one before, but you could use jQuery as that's even simpler;

var elems = $('.myClass');

Upvotes: 1

Related Questions