Tutorials using JS
Change width of Paragraph using JavaScript
In this tutorial, you shall learn how to change width of a paragraph element using JavaScript.
Solution
To set or change the width of a paragraph element using JavaScript, we can use Element.width
property. Get the paragraph element and set its width
property with the required length value.
paragraphElement.width = '200px';
Program
When user clicks on the Click me
button, we get the paragraph with the id message
, and set its width using width
property.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Tutorial</h1>
<button id="myBtn">Click me</button>
<p id="message">This is a paragraph. Welcome to JavaScript tutorials.</p>
<script>
document.getElementById("myBtn").addEventListener("click", function() {
//get the paragraph element
const myPara = document.getElementById("message");
//set the background color of the paragraph
myPara.style.width = '200px';
});
</script>
</body>
</html>