Search code examples
javascriptjquery-selectorscustom-element

this is defined, but children and querySelector fail for custom element


I have a custom element (input-date) inside another custom element (edit-table). When I go to assign the value to the input-date, inside the 'set value' class member function i log:

 console.log(this)

prints out the element

<input-date id=​"cell" style=​"height:​ 100%;​ width:​ 300px;​">
  ​<input id=​"input" placeholder=​"mm/​dd/​yyyy, hh:​mm am/​pm" style=​"font-family:​ "Open Sans", sans-serif;​ height:​ 100%;​ width:​ 100%;​ text-align:​ left;​ font-size:​ 18px;​ border:​ 2px;​ border-radius:​ 5px;​ padding:​ 5px;​">​
</input-date>​

but when i do

 console.log(this.children);

and

 console.log(this.querySelector('#input'));

I get 'null'.

the function with 'this' is inside 'set value' of my input-date class

class InputDate extends HTMLElement
{
...
connectedCallback()
{
  var input = document.createElement('Input');
  input.id = 'input';
  this.appendChild(input);
}
set value(val)
{
  //val should be a date object 
  var i = this.querySelector('#input');
  if(i && val)
  {
    i.value = val.toLocaleString();
  }
  console.log(i,val,this, this.childNodes);
}
...
customElements.define('input-date',InputDate);

note: also if its relevant, my_date.value = some_date; (the part that calls the 'set value' class member function) happens in a completion block from an XMLHTTPRequest to an API.

the input-date is created inside another custom element called edit-table.

so i set the users in 'edit-table'

get_users(function(r)
{
  if(r.hasOwnProperty('error_message'))
  {
    alert(r.error_message);
  }
  else
  {
    var table   = document.getElementById('edit-table');
    table.users = r.users;  
  }
});

then under 'edit-tables' 'set users', i create an 'input-date' element and try to assign the date from the server, (which is Wed Feb 08 2017 00:00:00 GMT-0500)

class EditUsers extends HTMLElement
...
set users(users)
{  
  ...
  var check  = document.createElement('input-date');
  check.value = new Date('Wed Feb 08 2017 00:00:00 GMT-0500');
}
customElements.define('edit-table',EditTable);
}

any ideas?


Solution

  • wow! Cant believe it. i've been making this mistake for years now and am still doing it....

    i need to do 'appendChild' of my custom-element BEFORE doing

     my_element.value = new Date();
    

    because until 'appendChild' is called, the 'connectedCallback()' is not called yet, and therefore the 'input' element is not appended to my custom-element yet, and therefore the 'querySelector' cant find the child yet.

    thanks @mickers, I didnt want to bog down the details, but this is what happened. Hopefully helps someone