-3

I have this:

<script id="wpcp_css_disable_selection" type="text/javascript">
    var e = document.getElementsByTagName('body')[0];
    e.setAttribute('unselectable','on');
</script>

How come that the console throws this:

Uncaught TypeError: Cannot read property 'setAttribute' of undefined
  • If `getElementsByTagName` doesn't return any elements, getting element `[0]` will return `undefined`. – lonesomeday Dec 13 '14 at 17:31
  • 1
    You know you can just do `document.body`, assuming the element is available of course, which it seems it's not ! – adeneo Dec 13 '14 at 17:32
  • 2
    If that ` – Pointy Dec 13 '14 at 17:35
  • @"Edward Norton": Could you give us feedback to avoid speculative answers/comments? – dotpush Dec 13 '14 at 19:38

2 Answers2

0

what about

<body onload="myFunction()">

and

<script id="wpcp_css_disable_selection" type="text/javascript">
  function myFunction(){
    var e = document.getElementsByTagName('body')[0];
    e.setAttribute('unselectable','on');
  };      
</script>

which makes sure, DOM is set up and then function will be called. i suspect DOM is not ready yet when your function is called. just a guess. may also be wrong

doniyor
  • 36,596
  • 57
  • 175
  • 260
  • onload is never a good idea when you may depend, now or later, on external ressources. – dotpush Dec 13 '14 at 17:41
  • "External ressources" might be a facebook javascript, a JS externally stored, or a lot of other things you have no control on. When the servers you don't own are not responding (or are affected by network issues), the load event can happen too late. – dotpush Dec 13 '14 at 17:48
  • Your code cares about the same than window.onload. Unless I'm wrong and [an accepted answer well rated answer](http://stackoverflow.com/a/191318/1106814) too. And if this question author don't ask about external resources, unless he explicitly tells he is sure to never use them, why encourage to something that seems to be, in a general case, a bad habit causing hard to reproduce bugs? – dotpush Dec 13 '14 at 19:35
-1

I think the body element should be in the HTML page. You can check it like this:

var e = document.getElementsByTagName('body');
if(typeof e != 'undefined'){
    e[0].setAttribute('unselectable','on');
}
Riad
  • 3,822
  • 5
  • 28
  • 39
  • All this does is suppress the error. It doesn't actually do anything. – JJJ Dec 13 '14 at 18:14
  • @Juhana: Although I disagree with this code alone, preventing `Uncaught TypeError` is far from doing anything. – dotpush Dec 13 '14 at 19:41
  • @dotpush Right, but the OP's goal is to set the "unselectable" attribute on the body tag. This code doesn't do that. This is equivalent of just commenting out the whole code. – JJJ Dec 14 '14 at 08:06
  • That's why I started the comment by saying I disagree with the code of the answer. – dotpush Dec 14 '14 at 15:53