milano
milano

Reputation: 475

How to find width of div inside another div using JQuery

Hi I am trying to run this code that finds the width of div which is inside another div. but it is not running properly. How to do this?

i want the width of div mitem1

Code:

<!DOCTYPE html>
<html>
    <head>
    <style type="text/css">
        div#mydiv {
            width: 100px;
            height: 100px;
            background-color: red;
        }
    </style>
    <script language="JavaScript">
        $('.menubar').each(function(menu){
            var len = $(this).find('.mitem').text().length;
            alert(len);
        });
    </script>
    </head>
    <body>

        <div class="menubar">

            <table border="1"><tr>
                <td><div class="mitem1">Home</div></td>
                <td><div class="mitem1">Communities<ul><li>item1</li><li>item2</li><li>item3</li><li>item4</li><li>item5</li></div></td>
                <td><div class="mitem1">Project Gallery</div></td>
                <td><div class="mitem1">For Our Customer</div></td>
                <td><div class="mitem1">Our Services</div></td>
            </tr></table>

        </div>

    </body>
    </html>

Upvotes: 3

Views: 444

Answers (2)

user1823761
user1823761

Reputation:

ISSUE 1

You forgot to add jQuery in your page. Add it:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

ISSUE 2

You must put your code in document ready:

$(function () {
});

ISSUE 3

Now you can iterate over your items, and for accessing the width of element, use .width() method in jQuery:

$(function () {
    $('.menubar .mitem1').each(function() {
        var width = $(this).width();

        // now do anything you want with width
    });
});

Upvotes: 3

billyonecan
billyonecan

Reputation: 20250

$('.menubar .mitem1').each(function() {
  alert($(this).width());
});

Here's a fiddle

If you want to get the width, including the padding and border (and margin, optional), use outerWidth()

Upvotes: 8

Related Questions