Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 638
Abrar Jahin Avatar asked Jan 31 '15 23:01

Abrar Jahin


People also ask

How do you find the width of a parent element?

To get the parent height and width in React: Set the ref prop on the element. In the useEffect hook, update the state variables for the height and width. Use the offsetHeight and offsetWidth properties to get the height and width of the element.

How do you find the width of an element?

The offsetWidth property returns the viewable width of an element (in pixels) including padding, border and scrollbar, but not the margin. The offsetWidth property is read-only.

How do you find the parent element?

To get the parent node of an HTML element, you can use the parentNode property. This property returns the parent node of the specified element as a Node object. The parentNode property is read-only, which means you can not modify it.

How do you take full width of a parent DIV?

Method 2: We can make the display attribute of the child container to table-row and display attribute of parent container to table, that will take all the height available from the parent div element. To cover all the width, we can make the width of parent div to 100%.


1 Answers

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>
like image 118
Oriol Avatar answered Sep 29 '22 06:09

Oriol