2

i have a problem when i try to hide/show an element in the DOM using the javascript call document.getElementById(elemId).style.visibility = visible/hidden.

This is a very strange behaviour , when i get the DOM element by id and set the visibility to visible, in the console i can see that the inline style have been modified but the element on the screen is still hidden.

I'll link a fiddle example of my problem, hope someone can help

This is the function i'm using to hide/show DOM elements

function updateHTML(elmId, value) {
  var elem = document.getElementById(elmId);
  if (typeof elem !== 'undefined' && elem !== null) {
    document.getElementById(elmId).style.visibility = value;
    console.log(elem);
  }
}

Anyway even the direct call document.getElementById('2').style.visibility = 'visible' is not working

PS What i'm trying to achieve is to show the span over the exclamation mark that is, for css default, hidden

Fiddle Demo

Nic
  • 163
  • 3
  • 19

2 Answers2

1

When you call the updateHtml the element has not been created yet.

For testing added the updateHtml inside a timeout call after 1s and it works.

setTimeout(() => updateHTML("8", "visible"), 1000);

jsfiddle demo

MaanooAk
  • 2,418
  • 17
  • 28
  • YOU MADE MY DAY! Thanks a lot for the hint – Nic Apr 05 '18 at 08:21
  • Maanoo i want to show you this other fiddle. https://jsfiddle.net/boLtzbvq/ is the same example as before but some elements are generated dynamically. This time your solution is not working :( Have you some hints to spare? :) – Nic Apr 05 '18 at 09:40
  • 1
    @Nic added a correct listener instaed of a timeout and generated the spots first and then added them to the config https://jsfiddle.net/boLtzbvq/30/ (sorry for the delay) – MaanooAk Apr 05 '18 at 10:52
  • MaanooAk you have been faster than light and AGAIN you solved my problem. Many many thanks :) – Nic Apr 05 '18 at 12:45
0

I checked your fiddle, but the id that you mentioned to the following code does not exist:

updateHTML("8", "visible");

Into your update function you do this ...

function updateHTML(elmId, value) {
  var elem = document.getElementById(elmId); // <- this line
  if (typeof elem !== 'undefined' && elem !== null) {
    document.getElementById(elmId).style.visibility = value;
    console.log(elem);
  }
}

But you get the id of unexisting element.

Other things:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Radonirina Maminiaina
  • 6,958
  • 4
  • 33
  • 60