0

I've seen other posts with the same title. Why does jQuery or a DOM method such as getElementById not find the element? does not apply. I am not looking for the ID before the html is loaded. Here is the whole file:

https://jsfiddle.net/2uxqmsth/ If you click on the link - the function is called. The relevant javascript is below:

    function getNewComment() {
        var xd = document.getElementById('#xdialog');

        if ( xd === null ) alert( 33 );
        else alert( 22 );
    }
Community
  • 1
  • 1
gene
  • 156
  • 2
  • 11
  • dont youse # in id – Sumanth Jois Apr 11 '16 at 02:21
  • 1
    `getElementById('xdialog')` not `getElementById('#xdialog')` – j08691 Apr 11 '16 at 02:21
  • 1
    Thanks all. have not use js in a while... I deserve -1. – gene Apr 11 '16 at 02:23
  • Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) — _“[…] `document.querySelector('#elementID')`, as opposed to the method by which an element is retrieved by its `id` under `document.getElementById('elementID')`; in the first the `#` character is essential, **in the second it would lead to the element not being retrieved.**”_ (emphasis mine) — already answered by the second answer. – Sebastian Simon Apr 11 '16 at 02:29

4 Answers4

2
 var xd = document.getElementById('#xdialog');

change this to

 var xd = document.getElementById('xdialog');
Sumanth Jois
  • 2,862
  • 2
  • 21
  • 35
2

You are mixing javascript with JQuery.

If you want to use javascript then it will be

var xd = document.getElementById('xdialog');

and not

var xd = document.getElementById('#xdialog');

If you want to use Jquery,then use like this:-

var xd = $("#xdialog");
Naruto
  • 3,847
  • 1
  • 18
  • 30
0

getElementById takes an ID, not a selector.

Your ID doesn't have a #.

SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896
0

Check out the following documentation for document.getElementById()

You'll need to remove the # from your id, so your snippet should instead look like the following:

function getNewComment() {
  var xd = document.getElementById('xdialog');

  if ( xd === null ) alert( 33 );
  else alert( 22 );
}
Sean3z
  • 3,375
  • 5
  • 23
  • 30