简体   繁体   中英

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>
$('.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()

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
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM