1

I am new to javascript and I want to get the elements by the name with help of loop but can not get the elements. Kindly help so that i can reduce the lot of code by using loop.

Below are the lines of code

function (e){
    for(var i=1;i<5;i++){
        var name = "qption0"+i;
        var clicableObject = document.getElementById(name);
        clicableObject.backgroundColor = "#00FF00";
    }
}

Above code is in JAVASCRIPT

3
  • You mention get element by name, yet you're using getElementById... If the IDs of your controls aren't qption01-04 then this approach won't work. Commented Dec 3, 2012 at 10:32
  • 1
    You say you want to get the elements by the name, but you're using getElementById Commented Dec 3, 2012 at 10:33
  • Are you trying to get it by name or by id? Commented Dec 3, 2012 at 11:06

3 Answers 3

1

You can simply do this:-

var name = "qption0"+i;
var clicableObject = document.getElementsByName(name);
clicableObject.style.backgroundColor = "#00FF00"

Thats it.. Hope it helps...

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

3 Comments

This is a comment, not an answer.
@kmb385 Ya...actually I am a newbiee at stackoverflow :p..But now i have turned it into an answer..:)
excellent work. I encourage you to keep visiting the community, its pretty easy to get the hang of the site.
0

When changing an elements background color via Javascript the syntax of the statement is elem.style.backgroundColor. The provided code omits the .style. portion of this call.

function (e){
    for(var i=1;i<5;i++){
        var name  = "qption0"+i;
        var clicableObject  = document.getElementById(name);        
        clicableObject.style.backgroundColor = "#00FF00"; //notice .style.back..
}

For further information check out this article on MDN.

Comments

0

You should use style object..

clicableObject.style.backgroundColor = "#00FF00";

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.