The attr() method is returning "undefined" value of (v) when used with alert. Can someone help please?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#decw").click(function() {
$("#cht").attr("width",function(n, v) {
alert(v);
return v - 50;
});
});
});
</script>
</head>
<body>
<div id="cht" style="width:284px; height:213px; background-color:red"></div><br><br>
<button id="decw">Decrease Width by 50px</button>
</body>
</html>
2
Answers
In the official docs, it’s stated as
The
div
does not havewidth="..."
attribute, therefore it returnsundefined
You can use
.width()
to get, decrease and set the width of thediv
Your issue is because the
width
is not an attribute – it’s set in CSS.To do what you require you could use the
css()
method instead:Or alternatively, the
width()
method. Note thatparseInt()
isn’r required here as the argument has already been coerced to an integer.