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.
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.
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.
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.
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%.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With