Franco Roura
Franco Roura

Reputation: 817

Why is this Javascript not hiding the HTML items?

I made a script that's supposed to hide a certain item of an HTML list but it's not working. I reviewed the code several times yet I can't find what's wrong with it.

This is the function I've been using:

  hidecba() {
     var cba = document.getElementById('cba');
     cba.style.display = 'none';
 }
 hidestafe() {
     var stafe = document.getElementById('stafe');
     stafe.style.display = 'none';
 }
 hidebsas() {
     var bsas = document.getElementById('bsas');
     bsas.style.display = 'none';
 }

And this is the HTML code that it's supposed to hide:

<ul id="lista1">
    <li id="cba" value="cba" onclick="hidecba()">Córdoba</li>
    <li id="stafe" value="stafe" onclick="hidestafe()">Santa Fe</li>
    <li id="bsas" value="bsas" onclick="hidebsas()">Buenos Aires</li>
</ul>

Also, here's a JSFiddle with the HTML and Javascript altogether:

https://jsfiddle.net/fxwfran/6vp1ugcb/2/

Upvotes: 2

Views: 71

Answers (2)

Colin.W
Colin.W

Reputation: 1

Bad

*function* hidecba(){
var cba = document.getElementById('cba');
cba.style.display='none';
}

Good

<ul id="myul">
    <li>click me1</li>
    <li>click me2</li>
    <li>click me3</li>
    <li>click me4</li>
</ul>
var myul=document.getElementById("myul");
    function hideEle(ele){
        ele.style.display='none';
    }
    myul.addEventListener('click',function(e){
        hideEle(e.target)
    });

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074979

If you look in the web console, you'll see an error there. (Top tip: Use the tools the browser gives you.)

You're missing the word function:

    function hidecba(){
//  ^^^^^^^^
        var cba = document.getElementById('cba');
        cba.style.display='none';
    }

There are also all kinds of other issues with that fiddle, such as:

<li id="tucu" value="tucu" onclick="function(#tucu)">Tucumán</li>
  1. li elements have no value attribute

  2. The JavaScript in the onclick attribute is invalid (function is not a function name)

  3. If function were a function name, you'd need quotes around #tucu.

  4. But ideally, you'd just use this, since it already refers to the element

Here's a simple example of hiding a list item when you click it using an onxyz handler:

function hideElement(element) {
  element.style.display = "none";
}
<ul>
  <li onclick="hideElement(this)">Click to hide (1)</li>
  <li onclick="hideElement(this)">Click to hide (2)</li>
  <li onclick="hideElement(this)">Click to hide (3)</li>
  <li onclick="hideElement(this)">Click to hide (4)</li>
</ul>

...but I wouldn't use onxyz attributes for this. I suggest reading up on addEventListener (and its Microsoft cousin attachEvent).

Upvotes: 3

Related Questions