How to change the attribute of an element in javascript?

Asked

Viewed 252 times

1

function changedisplay()
{
    var x = document.getElementsByTagName('li');
    if (x.style.display == 'none')
    {
        x.style.display  = 'block';
    }
    else
    {
        x.style.display  = 'none';
    }
    
}
<!DOCTYPE html>
<html>
    <HEAD>
        <meta charset='utf-8'>
        <script type='text/javascript' src='script.js'></script>        
    
        <style>
            li
            {
                display: none;

            }
            

        </style>
    </HEAD>

    <body>

        <button onclick="changedisplay()">mudar</button>
        <ul>
            <li name='li'>ASDASD</li>
            <li name='li'>ASDASD</li>
            <li name='li'>ASDASD</li>
        </ul>
  
</body>
</html>

I’m trying to make a menu for mobile with a <ul> by default is display: None, I want to change the msm block when the user clicks the Menu to give the effect and return to None when it is pressed.

1 answer

1


getElementsByTagName returns a list of several elements (to be more precise, returns a HTMLCollection), then you need to go through this list, and for each element, change the style of the same:

for (let x of document.getElementsByTagName('li')) {
  if (!x.style.display || x.style.display == 'none')
    x.style.display  = 'block';
  else
    x.style.display  = 'none';
}

Or:

let elementos = document.getElementsByTagName('li');
for (let i = 0; i < elementos.length; i++) {
  let x = elementos[i];
  if (!x.style.display || x.style.display == 'none')
    x.style.display  = 'block';
  else
    x.style.display  = 'none';
}

I also included one more condition (!x.style.display), because the first time the display elements may not be defined.

Full example:

function changedisplay()
{
    for (let x of document.getElementsByTagName('li')) {
      if (!x.style.display || x.style.display == 'none')
        x.style.display  = 'block';
      else
        x.style.display  = 'none';
    }
}
<!DOCTYPE html>
<html>
    <HEAD>
        <meta charset='utf-8'>
        <script type='text/javascript' src='script.js'></script>        
    
        <style>
            li
            {
                display: none;

            }
            

        </style>
    </HEAD>

    <body>

        <button onclick="changedisplay()">mudar</button>
        <ul>
            <li name='li'>ASDASD</li>
            <li name='li'>ASDASD</li>
            <li name='li'>ASDASD</li>
        </ul>
  
</body>
</html>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.