- How to Change Height of Div in JavaScript?
- Conclusion
- Related Tutorials
- Popular Courses by TutorialKart
- Salesforce
- SAP
- Accounts
- Database
- Programming
- App Developement
- Mac/iOS
- Apache
- Web Development
- Online Tools
- Javascript изменить высоту элемента
- # Set the Width and Height of an Element using JavaScript
- # Setting width and height has no effect on inline elements
- # Setting the element’s display to inline-block
- # Set the Width and Height on a Collection of Elements
- # Additional Resources
- Изменение размеров div на JavaScript
- Комментарии ( 3 ):
How to Change Height of Div in JavaScript?
To change the height of a div using JavaScript, get reference to the div element, and assign required height value to the element.style.height property.
Conclusion
In this JavaScript Tutorial, we learned how to change the height of a div using JavaScript.
Related Tutorials
- How to Change Border Color of Div in JavaScript?
- How to Change Border Radius of Div in JavaScript?
- How to Change Border Style of Div in JavaScript?
- How to Change Border Width of Div in JavaScript?
- How to Change Bottom Border of Div in JavaScript?
- How to Change Font Color of Div in JavaScript?
- How to Change Font Family of Div in JavaScript?
- How to Change Font Size of Div in JavaScript?
- How to Change Font Weight of Div in JavaScript?
- How to Change Left Border of Div in JavaScript?
- How to Change Margin of Div in JavaScript?
- How to Change Opacity of Div in JavaScript?
- How to Change Padding of Div in JavaScript?
- How to Change Right Border of Div in JavaScript?
- How to Change Text in Div to Bold in JavaScript?
- How to Change Text in Div to Italic in JavaScript?
- How to Change Top Border of Div in JavaScript?
- How to Change Width of Div in JavaScript?
- How to Change the Background Color of Div in JavaScript?
- How to Change the Border of Div in JavaScript?
- How to Clear Inline Style of Div in JavaScript?
- How to Hide Div in JavaScript?
- How to Insert Element in Document after Specific Div Element using JavaScript?
- How to Underline Text in Div in JavaScript?
- How to get Attributes of Div Element in JavaScript?
Popular Courses by TutorialKart
Salesforce
SAP
Accounts
Database
Programming
App Developement
Mac/iOS
Apache
Web Development
Online Tools
©Copyright — TutorialKart 2023
Javascript изменить высоту элемента
Last updated: Jan 11, 2023
Reading time · 3 min
# Set the Width and Height of an Element using JavaScript
Use the style.width and style.height properties to set the width and height of an element, e.g. box.style.width = ‘100px’ .
The width and height properties set the element’s width and height to the supplied values.
Here is the HTML for the examples.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> div id="box" style="background-color: salmon">Box 1div> script src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!const box = document.getElementById('box'); // ✅ Set width to 100px box.style.width = '100px'; // ✅ Set height to 100px box.style.height = '100px';
The style object allows us to set, read or update any CSS property on the element.
Copied!const box = document.getElementById('box'); // ✅ Set width to 100px box.style.width = '100px'; // ✅ Set height to 100px box.style.height = '100px'; console.log(box.style.width); // 👉️ "100px" console.log(box.style.height); // 👉️ "100px"
# Setting width and height has no effect on inline elements
Note that setting the width and height on an inline element, such as a span has no effect.
Copied!DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> title>bobbyhadz.comtitle> head> body> span id="box" style="background-color: salmon">Box 1span> script src="index.js"> script> body> html>
And here is our attempt to update the element’s height and width.
Copied!const box = document.getElementById('box'); // ❌ Set width to 100px box.style.width = '100px'; // ❌ Set height to 100px box.style.height = '100px';
If you open your browser, you will see that the element’s width and height are determined by the content area.
# Setting the element’s display to inline-block
To solve this, we can set the element’s display property to inline-block .
Copied!DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> span id="box" style="background-color: salmon; display: inline-block" >Box 1span > script src="index.js"> script> body> html>
And now we can set the element’s width and height.
Copied!const box = document.getElementById('box'); // ✅ Set width to 100px box.style.width = '100px'; // ✅ Set height to 100px box.style.height = '100px';
Some examples use the setAttribute method to update the element’s height and width, however, the setAttribute method overrides the style property completely.
Copied!const box = document.getElementById('box'); box.setAttribute('style', 'width: 100px; height: 100px');
The setAttribute method takes 2 parameters:
- The name of the attribute we want to set on the element.
- The value that should be assigned to the attribute.
If the attribute already exists, the value is updated, otherwise, a new attribute is added with the specified name and value.
So if you use the setAttribute method approach, you are effectively replacing the element’s style attribute value.
This can be very confusing and difficult to debug, so it’s best to set any CSS properties using the style object on the element.
# Set the Width and Height on a Collection of Elements
If you need to set the width and height on a collection of elements, you have to:
- Select the collection of elements.
- Use the for. of method to iterate over the collection.
- Set the width and height using the style.width and style.height property on each element.
Copied!DOCTYPE html> html lang="en"> head> title>bobbyhadz.comtitle> meta charset="UTF-8" /> head> body> div class="box" style="background-color: salmon">Box 1div> div class="box" style="background-color: salmon">Box 2div> div class="box" style="background-color: salmon">Box 3div> script src="index.js"> script> body> html>
And here is the related JavaScript code.
Copied!const boxes = document.querySelectorAll('.box'); for (const box of boxes) box.style.width = '100px'; box.style.height = '100px'; >
We used the document.querySelectorAll method to select all elements with a class of box .
We then used the for. of loop to iterate over the collection and set the width and height properties on each element.
# Additional Resources
You can learn more about the related topics by checking out the following tutorials:
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
Изменение размеров div на JavaScript
Мы с Вами когда-то разбирали перемещение div на JavaScript, а сегодня мы разберём изменение размеров div на JavaScript, которое так же может быть очень удобно для пользователей сайта.
Для начала разберём HTML-код:
Думаю, тут всё более чем понятно. Что касается «block_resize«, то именно его и надо будет «тянуть» для изменения размеров блока.
#block background-color: #ff0;
min-height: 100px;
min-width: 200px;
position: relative;
width: 400px;
>
#block_resize background-color: #000;
bottom: 0;
cursor: se-resize;
height: 12px;
margin-top: 9px;
position: absolute;
right: 0;
width: 12px;
>
Теперь разберём самое главное и самое сложное — код JavaScript:
Код я постарался хорошо прокомментировать, поэтому разобраться в нём можно. Если Вы читали про перемещение div с помощью JavaScript, то Вы заметили огромную схожесть, что неудивительно, ведь используется тот же механизм drag-and-drop.
В любом случае, даже если Вы затрудняетесь в понимании кода, Вы можете его копировать, заменив только имена блоков, и вставить к себе на сайт. Никаких jQuery данный код не требует, что также является большим преимуществом данного скрипта.
Создано 23.09.2013 08:40:32
Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!
Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.
Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления
Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.
Порекомендуйте эту статью друзьям:
Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):
- Кнопка:
Она выглядит вот так: - Текстовая ссылка:
Она выглядит вот так: Как создать свой сайт - BB-код ссылки для форумов (например, можете поставить её в подписи):
Комментарии ( 3 ):
извеняюсь что не в тему! Миша, я тут увидел у тебя на сайте опрос по будущему видеокурсу, и хотел бы тебя спросить, сколько будет примерно он стоить, если выбирут социальную сеть?
Ещё пока ничего неизвестно.