bamblack
bamblack

Reputation: 3779

Uncaught TypeError: Cannot set property 'Width' of undefined

I'm having an issue dynamically setting the width of a ul element in my website.

Below is the jQuery I'm uusing

var button = $("#navbar");
alert(button);
var count = $("#header li").length;
alert(count);
$("#navbar").style.Width = count * 110

Here's the HTML

<div id="header" class="clearfix">
    <div class="clearfix hidden">
        <img src="/Content/Images/main-logo.png">
    </div>
    <div id="navbar">
        <ul>
            <li id="home">
                home
            </li>
            <li id="portfolio">
                portfolio
            </li>
            <li id="about">
                about
            </li>
        </ul>
    </div>
</div>

The "alert(button)" returns [object Object] so it's not null (at least my understanding of it) but I get the error mentioned in the title whenever I try to set the width of it.

Anyone know what I'm doing wrong?

Upvotes: 2

Views: 9603

Answers (3)

rexcfnghk
rexcfnghk

Reputation: 15452

You are working on a jQuery element by using $("#navbar"). If you want to set the width using vanilla javascript:

$("#navbar")[0].style.width = count * 110  //note that the width property is not capitalized

Or use jQuery's width method:

$("#navbar").width(count * 110);

Upvotes: 1

Hieu Le
Hieu Le

Reputation: 8415

You must use one of the following code

$("#navbar")[0].style.width = count * 110

or

$("#navbar").width(count * 110)

because the style is the property of DOM element while $("#navbar") is a jquery object, which does not contain the style property by default.

Upvotes: 5

takteek
takteek

Reputation: 7110

style is a DOM property but not a property of jQuery objects. If you want to set the width using jQuery you'd use either the css getter/setter or the width function directly.

$("#navbar").width(count * 110);
$("#navbar").css('width', (count * 110) + "px");

Upvotes: 1

Related Questions