jQuery attr() method is used to get first selected element or set attribute value to matched all elements.
Get current attribute value for first matched content:
$(selector).attr(attribute);
Set the new attribute and value to all matched elements:
$(selector).attr(attribute,value);
Set multiple new attribute and value to all matched elements:
$(selector).attr({attribute:value, attribute:value...});
attribute is attribute name of element
value attribute value to set on element
Below example shows how to get images source link using button click.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img src="https://laravelcode.com/assets/images/logo.png" alt="laravelcode" />
<button>Get image link</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('button').click(function() {
var link = $('img').attr('src');
alert(link);
});
});
</script>
</body>
</html>
If you want to change or add new attribute, pass the second parameter as attribure value.
Here is the example to change image changing src value.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img src="https://laravelcode.com/assets/images/logo.png" alt="laravelcode" /><br>
<button>Get image link</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('button').click(function() {
$('img').attr('src', 'https://laravelcode.com/images/password-generator.jpg');
});
});
</script>
</body>
</html>
If you want to change multiple attribute value to all matched elements, pass them to json object.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img src="https://laravelcode.com/assets/images/logo.png" title="laravelcode" /><br>
<button>Get image link</button>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('button').click(function() {
$('img').attr({src:'https://laravelcode.com/images/password-generator.jpg', title: 'Password generator', width: '200px'});
});
});
</script>
</body>
</html>
I hope it will help you.
Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]
OnScroll Load More in Laravel 8 with Livewire Package
In this article, i will share with you h...VueJs CRUD using Google Firebase
This is a step by step tutorial that exp...Single and Multiple Files Upload in VueJs
In this tutorial, we are going to learn...Class 'App\Http\Controllers\ZipArchive' not found in Laravel
While working on Zip file in your Larave...Syntax error or access violation: 1055 'posts.views' isn't in GROUP BY
While working with Laravel database quer...