Home > Software design >  jQuery .attr() method returning undefined attribute value
jQuery .attr() method returning undefined attribute value

Time:08-21

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>

CodePudding user response:

In the official docs, it's stated as

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set.

The div does not have width="..." attribute, therefore it returns undefined

You can use .width() to get, decrease and set the width of the div

<!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() {
        const newWidth = $("#cht").width() - 50;
        $("#cht").width(newWidth);
      });
    });
  </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>

CodePudding user response:

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:

$(document).ready(function() {
  $("#decw").click(function() {
    $("#cht").css("width", (i, v) => parseInt(v, 10) - 50);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="cht" style="width:284px; height:213px; background-color:red"></div><br><br>
<button id="decw">Decrease Width by 50px</button>

Or alternatively, the width() method. Note that parseInt() isn'r required here as the argument has already been coerced to an integer.

$(document).ready(function() {
  $("#decw").click(function() {
    $("#cht").width((i, w) => w - 50);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="cht" style="width:284px; height:213px; background-color:red"></div><br><br>
<button id="decw">Decrease Width by 50px</button>

  • Related