Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   
   HTML   
   CSS   
   JAVA SCRIPT   
   JQUERY   




HTML METHODS - width()


The width() method in JQuery is used to get and set the width of an HTML element.


width() as Getter method


Example :



<html>
  	<head>
    	<title> My First Programme </title>
    	
    	<script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script>
  	</head>

  	<body>
    	<h1> JQuery </h1>
    	
    	<p style = "background-color:violet; height:100px; width:150px"> Hello World </p>
        
        <button> Click it </button> 
	  
      	<script>
      
			$('button').click( function() { 
            	alert("The width of the p element is : "+$('p').width());
            });
            
      	</script>
  	</body>
</html>


Output :




So, if we look at the above code, we have a <p> element.


<p style = "background-color:violet; height:100px; width:150px"> Hello World </p>

And we have a <button> element,


<button> Click it </button>

And on button click, the JQuery statement gets triggered,


$('button').click( function() {
	alert("The width of the p element is : "+$('p').width());
});

And an alert is generated,


alert("The width of the p element is : "+$('p').width());

Now, if we see the output (i.e. The alert),


You get the width of the <p> element (i.e. 150).


This is because the width() method is used to get the width of the <p> element.

JQuery HTML Methods width()

width() as Setter method


Example :



<html>
  	<head>
    	<title> My First Programme </title>
    	
    	<script src = "https://cdnjs.cloudflare.com/ajax/libs/JQUERY/3.3.1/jquery.min.js"> </script>
  	</head>

  	<body>
    	<h1> JQuery </h1>
    	
    	<p style = "background-color:violet; height:100px;"> Hello World </p>
        
        <button> Click it </button> 
	  
      	<script>

                $('button').click(function(){
                  $('p').width("150px");
                });
                
      	</script>
  	</body>
</html>


Output :




So, if we look at the above code, we have a <p> element.


<p style = "background-color:violet; height:100px;"> Hello World </p>

And we have a <button> element,


<button> Click it </button>

And on button click, the JQuery statement gets triggered,


$('button').click( function() {
	$('p').width("150px");
});

And the width() method is used to set the width of the <p> element to 150px.


$('p').width("150px");

Now, if we see the output, the width of the <p> element got set to 150px.