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?
if document.getElementById(id).style.width
returns "10px"
then document.getElementById(id).style.width += 40 + "px"
will be "10px40px"
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.