Set and Get Methods
Set and Get Methods
1. val() Method
This is commonly used to get or set the value of form elements
like <input>, <select>, <textarea>, etc.
javascript
Copy code
var value = $('#myInput').val(); // Gets the current value of the input field with id
'myInput' console.log(value);
javascript
Copy code
$('#myInput').val('new value'); // Sets the value of the input field to 'new value'
2. text() Method
This method is used to get or set the plain text content of an element (it strips out any
HTML tags).
javascript
Copy code
var text = $('#myDiv').text(); // Gets the text content of the element with id 'myDiv'
console.log(text);
javascript
Copy code
$('#myDiv').text('New text content'); // Sets the text content of the element with id
'myDiv'
3. html() Method
This method is used to get or set the HTML content inside an element, including any
tags.
javascript
Copy code
var htmlContent = $('#myDiv').html(); // Gets the HTML content of the element with
id 'myDiv' console.log(htmlContent);
javascript
Copy code
$('#myDiv').html('<strong>New HTML content</strong>'); // Sets the HTML content
of the element
4. attr() Method
This method is used to get or set attributes of elements (like src, href, class, etc.).
javascript
Copy code
var srcValue = $('#myImage').attr('src'); // Gets the value of the 'src' attribute of the
image console.log(srcValue);
javascript
Copy code
$('#myImage').attr('src', 'new-image.jpg'); // Sets the 'src' attribute of the image to
'new-image.jpg'
Example of Using Set and Get Together:
You can combine these methods to change the content of elements dynamically based on
certain conditions.
javascript
Copy code
// Get the current value of an input field var currentValue = $('#myInput').val(); // If
the value is empty, set a new default value if (!currentValue) { $
('#myInput').val('Default value'); } // Get the new value and display it in an alert
alert($('#myInput').val());
Summary of Methods:
.val() — Get/set form element values (input, textarea, select).
.text() — Get/set text content (without HTML tags).
.html() — Get/set HTML content (with tags).
.attr() — Get/set attributes of elements.
These methods are the basic "get" and "set" functionalities provided by jQuery for
interacting with elements on the page.