Njam Hrum
Njam Hrum

Reputation: 11

Why this not working in JS?? getElementById().style.width += 40 + "px";

I'm trying to write a shorthand method getElementById().style.width += 40 + "px"; for changing element width in DOM via JavasScript but it isn't working. Any working solutions to achieve that?

Upvotes: 0

Views: 486

Answers (2)

Parth Patel
Parth Patel

Reputation: 824

Shorthand assignment is not possible. but you should try the following:

document.getElementById("div1").style.width = (parseInt(document.getElementById("div1").style.width) + 40) + "px";

Note: replace [id] with an appropriate id.

Full example code:

<html>
<head>
<title></title>
<script type="text/javascript">
    function incrementWidth() {
        document.getElementById("div1").style.width = (parseInt(document.getElementById("div1").style.width) + 40) + "px";
    }
</script>
</head>
<body>
  <div id="div1" style="height:100px;width:40px;background-color:orange;"></div>
  <button onclick="incrementWidth();">INCREMENT</button>
</body>
</html>

Upvotes: 1

Ian
Ian

Reputation: 159

if document.getElementById(id).style.width returns "10px"
then document.getElementById(id).style.width += 40 + "px" will be "10px40px"

Upvotes: 1

Related Questions