0

I'm trying to dynamically hide content from users who are not at least on a certain level.

All users can see level 1 content, but they will need to reach a higher level in order to see more content.

The level will be generated inside an html tag (id="level") through the use of a Wordpress plugin shortcode. The content for level 2 or higher will be hidden by default in the html div tag (id="myDiv").

I'm trying to change the style display property from myDiv through a javascript function.

function myFunction()
{
  var myDiv = document.GetElementById("myDiv");
  var level = document.GetElementById("level").innerHTML;
  if (level >= 2) {
      myDiv.style.display  = "block";
  } else {
    myDiv.style.display  = "none";
  }
}
<body onLoad="myFunction();">
  <div id="level">2</div>
  <div id="myDiv" style="display:none;">myDiv content</div>
</body>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
Jelz
  • 27
  • 8
  • 1
    You shouldn't do this in the front end. It's trivial to bypass the restriction - anybody can just open the developer tools and remove your protection. You should instead do the filtering on the backend and only give users the content they have access to. – VLAZ May 13 '21 at 12:44
  • Also: `GetElementById` should be `getElementById` – VLAZ May 13 '21 at 12:44
  • 1
    You should also [not be using inline HTML event attributes](https://stackoverflow.com/questions/43459890/javascript-function-doesnt-work-when-link-is-clicked/43459991#43459991) and avoid using inline CSS styles and instead add/remove/toggle CSS classes via the [`.classList` API](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList). – Scott Marcus May 13 '21 at 12:45
  • @VLAZ Thanks for highlighting this. Access is indeed managed from the backend, I'm only trying to manage visibility here. Access is granted/dripped on basis of a timeline, and I don't want users to see links to content they have not yet been granted access to. – Jelz May 14 '21 at 11:21

1 Answers1

1

Element.innerHTML will always return a string, try converting your innerHTML to a number using Number(level)

function myFunction()
{    
    let myDiv = document.getElementById("myDiv");
    let stringLevel = document.getElementById("level").textContent;
    const level = Number(stringLevel);
    if (level >= 2) {
        myDiv.style.display  = "block";
    } else {
        myDiv.style.display  = "none";
    }
}

(EDIT)

consider using textContent instead of innerHTML as pointed by Scott Marcus

  • 2
    Better yet, don't use `.innerHTML` at all and use `.textContent` since `.innerHTML` engages the HTML parser and introduces security and performance concerns. – Scott Marcus May 13 '21 at 12:49