-2

I need to use this JS but with a class and ID. Is this possible?

 document.getElementsById('container').style.marginLeft = '350px';

I tried this but it doesn't work

  document.getElementsByClassName('container').style.marginLeft = '350px';
Dev
  • 457
  • 6
  • 18

3 Answers3

2

document.querySelector('.container').style.marginLeft = '350px';
<div class="container" style="background: #000; width: 50px; height: 50px;"></div>
zhuravlyov
  • 503
  • 2
  • 11
1

getElementsByClassName returns a collection/array. So all you have to do it append the index number.

document.getElementsByClassName("whatever")[0] gets the first one.

Ronnie Royston
  • 16,778
  • 6
  • 77
  • 91
  • Yes but i already included that solution and i think .querySelector is a better solution in this specific case. – Dev Oct 07 '17 at 02:54
0

This worked.

  document.getElementsByClassName('container')[0].style.marginLeft = '350px';

And so does this which i think is better for my specific situation :

function openNav() {
    document.getElementById('side').style.width = '350px';
    document.querySelector('.container').style.marginLeft = '350px';
}
.sidenav {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    background-color: #111;
    overflow-x: hidden;
    transition: 0.5s;
    padding-top: 60px;
}

.sidenav a {
    padding: 8px 8px 8px 32px;
    text-decoration: none;
    font-size: 25px;
    color: #818181;
    display: block;
    transition: 0.3s;
}

.sidenav a:hover {
    color: #f1f1f1;
}

.sidenav .closebtn {
    position: absolute;
    top: 0;
    right: 25px;
    font-size: 36px;
    margin-left: 50px;
}

.container {
    transition: margin-left .5s;
    padding: 16px;
}
<!DOCTYPE html>
<html>
<body>

<div id="side" class="sidenav">
  <a href="#">About</a>
  <a href="#">Services</a>
  <a href="#">Clients</a>
  <a href="#">Contact</a>
</div>

<div class="container">
  <span style="font-size:30px;cursor:pointer" onclick="openNav()">&#9776;</span>
</div>

     
</body>
</html> 
Dev
  • 457
  • 6
  • 18