简体   繁体   中英

How to find a parent element width in JavaScript or jQuery?

I have a HTML code like this -

<div class="bs-example">
    <input type="text" id="typehead" style="width: 500px;" class="form-control" placeholder="accounts" />
    <input type="text" class="form-control" placeholder="accounts" />
</div>

I have to find the width of the parent element having ID typehead .

So in this case I have to find width of the div having class bs-example .

I can't use ID in the upper div so that I can have the width of the element by ID because I want a re-usable code because it should be used many places in the page .

What I have done is -

function myFunction()
{
    var x = document.getElementById("myLI").parentNode.parentElement.width;
    document.getElementById("demo").innerHTML = x;
}

But it is not working.

You can use

function parentWidth(elem) {
    return elem.parentElement.clientWidth;
}
parentWidth(document.getElementById('typehead'));

Note that it will throw if you call it with the argument document.documentElement . If you want it to return undefined instead of throwing, use parentNode instead of parentElement .

 function parentWidth(elem) { return elem.parentElement.clientWidth; } alert(parentWidth(document.getElementById('typehead')) + 'px');
 <div class="bs-example"> <input type="text" id="typehead" style="width: 500px;" class="form-control" placeholder="accounts" /> <br /> <input type="text" class="form-control" placeholder="accounts" /> </div>

var x = $("#typehead").parent().width();

You can use clientWidth property:

function myFunction() {
    var x = document.getElementById("myLI").parentNode.parentElement.clientWidth;
    document.getElementById("demo").innerHTML = x;
}

Update by Orion user (thank you) from the comments to this post:

Note this will retrieve the width used in the style content attribute, which may not be the same as the computed width

Here is a tidier example using JQuery: http://jsfiddle.net/srfqko8r/3/

<div style="width: 100px;">
    <div style="width: 50px;" id="child">
    </div>
</div>

function GetParentDivWidth(selector){
    return $(selector).parent("div").width();
}

$(function(){
   alert(GetParentDivWidth("#child"));
});

Alerts "100"

If you want a generic function you can use pass the element to check as parameter and use jQuery closest and width .

Code:

function myFunction($el) {
    return $el.closest('div.bs-example').width();
}

Demo: http://jsfiddle.net/f07uanoh/

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