Search code examples
javascriptappendchildchild-nodes

Understanding appendChild In JS in relation to the use of `this`


I'm having trouble understanding how to append created elements, so they are held within other created elements. If my explanation of this is confusing please let me know I'll try to clarify.

Context / Goal

The goal or context of this snippet is to create and track a character counter that dynamically adjusts in the users browser. The twist is; I needed it to apply to every <textarea></textarea> that may be on the page.

To help bring the users attention to the character counter, I wanted create a span to wrap around just the count i.e. 255. and adjust the color of the font dynamically when certain paramiters are met.

What I have currently

<div></div>

What I'm after

<div>
   <span id="cid0"></span>
</div> 

My JS - (See full script here - JSFiddle)

  // create wrapper & span element
  this.wrapper = document.createElement("div");
  this.span = document.createElement("span");
  this.span.id = "cid" +i;
  this.span.appendChild(this.wrapper);

  this.wrapper.innerHTML = 'Chars left: ';
  this.span.innerHTML = (this.MAX - input.value.length);

If anyone could clarify how to achieve what I am after, where I'm going wrong and if I have made a made a mistake I would be greatful for the assistance.


Solution

  • I think this is what you wanted to achieve

    <div>
       Chars left: <span id="cid0">xxxxx</span>
    </div> 
    

    Right? Then try this

      // create wrapper & span element
      this.wrapper = document.createElement("div");
      this.wrapper.innerHTML = 'Chars left: ';
      this.span = document.createElement("span");
      this.span.id = "cid" +i;
      this.span.innerHTML = (this.MAX - input.value.length);
    
      this.wrapper.appendChild(this.span);
    

    That should do the trick