Alexandru Ianas
Alexandru Ianas

Reputation: 105

Why doesn't it change the font size?

I've written a simple script in JavaScript to allow me to change the font size on a specific div (class) on my website, but it doesn't change it and I can't figure out why...

<script> //it gets the classname and set it font style to 20px
    function resizeText() {
        var x = document.getElementsByClassName("box2-li");
        x.style.fontSize="20px";
    };
</script>

This is the error I get when I press the button:

Uncaught TypeError: Cannot set property 'fontSize' of undefined

Why is that?

Upvotes: 3

Views: 4492

Answers (5)

Hooey Pooey
Hooey Pooey

Reputation: 1

I met the same problem, I suggest you use x[0].style.fontSize="20px"; instead of x.style.fontSize="20px";

Because Document.getElementsByClassName() return a list of matching elements, not the element itself.so you havse to choose first one to as your target.

MDN: Get the first element whose class is 'test'

Upvotes: 0

Sameera Thilakasiri
Sameera Thilakasiri

Reputation: 9508

x.className = "class-name-which-already-font-size-defined"

Above concept also can be used, result is you dont use in-line css. That is a best practice.

Upvotes: 0

Louis
Louis

Reputation: 132

You will have a collection, "Array" or elements in the variable 'x'.

You will need a for loop such as:

function resizeText() {
    var x = document.getElementsByClassName("box2-li");
    for (var i = 0; i < x.length; i++) {
        x[i].style.fontSize="20px";
    }
};

Upvotes: 4

Jose Luis Crisostomo
Jose Luis Crisostomo

Reputation: 15

You have to look into you ´css´ file into the block where you define ´box2-li´ and create the fontSize variable, I think this will fix your problem

Upvotes: 0

Tushar Gupta
Tushar Gupta

Reputation: 15913

The getElementsByClassName("box2-li"); gives a collection of elements not a single element, thus you cant change the font like x.

The collection is array like and can be accessed like x[0].style.fontSize="20px"; or you can use foreach to iterate each element

Upvotes: 6

Related Questions