Object is coming null

0

I have the following code, but the var ob is coming null.

<head>
<script>
   function pisca(item) {
       var ob = document.getElementById(item);

       if (ob.style.color=="red"){
          ob.style.color="black";
       }else{
          ob.style.color="red";
       }
   } 
</script>

</head>

<body>

<div id="piscar" style="color:#F00">
   Texto piscando
</div>

 <script>
    t = setInterval("pisca('piscar')",500);
 </script>

 </body>
    
asked by anonymous 06.04.2018 / 14:29

2 answers

0

I tried to simulate your problem here, but it did not.

function pisca(item) {
  var ob = document.getElementById(item);
  if (ob.style.color == "red") {
    ob.style.color = "black";
  } else {
    ob.style.color = "red";
  }
}

t = setInterval("pisca('piscar')", 500);
<div id="piscar" style="color:#F00">
  Texto piscando
</div>

Although I would change the way to call the function blinks in setInterval , after all this form is not recommended ( READ MORE )

function pisca(item) {
  var ob = document.getElementById(item);
  if (ob.style.color == "red") {
    ob.style.color = "black";
  } else {
    ob.style.color = "red";
  }
}

t = setInterval(function () {
  pisca('piscar')
}, 500);
<div id="piscar" style="color:#F00">
  Texto piscando
</div>
    
06.04.2018 / 14:38
0

Since the ob variable was declared with var within the pisca() function, it only has scope within the function.

You can solve it by making it global scope by removing var :

function pisca(item) {
    ob = document.getElementById(item);

    if (ob.style.color=="red"){
       ob.style.color="black";
    }else{
       ob.style.color="red";
    }
} 
  

After the function is executed, the variable ob becomes a value   global.

Example:

function pisca(item) {
    ob = document.getElementById(item);

    if (ob.style.color=="red"){
       ob.style.color="black";
    }else{
       ob.style.color="red";
    }
}

function teste(){
   console.log(ob);
}

pisca('piscar');
<div id="piscar" style="color:#F00">
   Texto piscando
</div>
<br>
<input type="button" onclick="teste()" value="Verificar valor de ob">
    
06.04.2018 / 15:55