Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 19, 2024 › #dynamically #Element

How to change width of div dynamically in JavaScript?

In this article, we'll explore two methods to dynamically change the width of a <div> element using JavaScript.

You'll learn why this can be useful and how to implement it step by step. By the end, you'll have a solid understanding of how to manipulate the width of a <div> element according to your needs.

Changing Width with the style Property #

To dynamically change the width of a <div> element using JavaScript, you can leverage the style property. This property allows you to manipulate the CSS properties of an element directly.

<div id="myDiv" style="background:red">This is a resizable div.</div>
<script>
  const myDiv = document.getElementById('myDiv');
  
  myDiv.style.width = '300px';
</script>

Explanation of the above example:

  1. First, select the <div> element you want to modify using JavaScript.
  2. Access the style property of the selected element using the style property.
  3. Set the width property of the style object to the desired value, specifying units like pixels (e.g. 200px) or percentages (e.g. 50%).

Toggling Width with the classList Property #

An alternative approach is to use the classList property to toggle between different width styles. This method is particularly useful when you want to switch between predefined width values.

<style>
  .wider {width: 100px}
</style>
<div id="myDiv" style="background:red">This div can change its width.</div>
<button>Toggle class</button>
<script>
  const myDiv = document.getElementById('myDiv');
  function toggleClass() {
    myDiv.classList.toggle('wider');
  }
  document.querySelector('button').addEventListener('click', toggleClass);
</script>

Explanation of the above example:

  1. We select the <div> element with the ID myDiv.
  2. By adding and removing CSS classes wider , you can toggle between different widths.

Conclusion: #

In this article, you learned how to dynamically change the width of a <div> element in JavaScript using two methods: the style property and the classList property.

save
listen
AI Answer
Write Your Answer
loading
back
View All