Ivaldir
Ivaldir

Reputation: 195

document.getElementsByClassName(variables);

I'm trying to target an element through the use of two variables. I know how to do this for id's, but what I'm doing for classes doesn't seem to works. Does anyone have an idea what I'm doing wrong?

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
    var colour = purple;
    var number = 1;
    function check() {
        var x = document.getElementsByClassName(colour number);
        x[0].innerHTML = "Hello World!";
    }
</script>
</head>
<body>
    <div>Username: </div>
    <input id="test" type="text" onblur="check()">
    <div class="1 purple">one</div>
    <div class="2 red">two</div>
    <div class="3 blue">three</div>
    <div class="4 brown">four</div>
    <div class="5 orange">five</div>
    <div class="6 yellow">six</div>
    <div class="7 white">seven</div>
</body>
</html>

Update

I've tried both options but neither seems to work. This is the updated script.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
    function check() {
        var colour = purple;
        var number = one;
        //var x = document.getElementsByClassName(colour + ' ' + number);
        var x = document.querySelector('.' + colour + '.' + number);
        x[0].innerHTML = "Hello World!";
    }
</script>
</head>
<body>
    <input id="test" type="text" onblur="check()">
    <div class="one purple">one</div>
    <div class="two red">two</div>
    <div class="three blue">three</div>
    <div class="four brown">four</div>
    <div class="five orange">five</div>
    <div class="six yellow">six</div>
    <div class="seven white">seven</div>
</body>
</html>

Also note, this is only a test script. Once I get it working, I'll add a lot more divs, one for each color/number combination, so selecting on one class will not work.

Upvotes: 0

Views: 736

Answers (2)

Strelok
Strelok

Reputation: 51481

You should construct a string:

var colour = 'purple';
var number = 1;
var x = document.querySelector('.'+colour+'.'+number);

Upvotes: 0

Guffa
Guffa

Reputation: 700690

The expression colour number is not a valid expression.

To specify the class names you need a string with space separated class names, for example "purple 1". Concatenate the strings with a space between them:

var x = document.getElementsByClassName(colour + ' ' + number);

However, as both the colors and numbers are unique, you only need to look for one of them:

var x = document.getElementsByClassName(colour);

or:

var x = document.getElementsByClassName(number);

Note: Class names that are only digits may be problematic in some situations. It's recommended that a class name doesn't start with a digit.

Upvotes: 2

Related Questions