Search code examples
javascriptcsssappersvelte-3svelte-component

using onMount to add class dynamically to element


Using sapper. Trying to create an input and assign 2 classes "name border" to that dynamically created input element. The element is created but the class is not applied. Not sure why and hoping someone woulud help me. The style section has two classes "name" and "border" and if I apply them to a regular input in my html, they work and applied to any input created like this:

<input class="name border"/>

But using dynamically created input, the styles classes not added to the created element. My simple component has the following:

 <script>
  import { onMount } from 'svelte';
    
  function getinfo(){
  let x = document.querySelectorAll('input')
  for (let i = 0; i < x.length; i++) {
                 let values = x[i].value;
                 console.log("input-value: ", values)
               } 
     
  }
  
       onMount( () => {
       
       var adiv = document.createElement('div');
       var firstinput = document.createElement('input')       
       firstinput.classList.add("name")
       adiv.appendChild(firstinput); 
      
    
       var parent = document.getElementById("parent");
       parent.appendChild(adiv);         
        
       // Apply the style class "name" settings to the input element
       document.querySelector("input").classList.add("name")
    
       var secondinput = document.createElement('input');      
       adiv.appendChild(secondinput);
       }
         
    ) //onMount
                
</script>

<style>
  /* to create a bigger input */
  .name{
  font-size: 16pt;
  height: 50px;
  }
          
  .border {
   border-style : solid;
  }

</style>

<h1> Enter Items </h1>

<form id="mainform" name="formcollect"  on:submit|preventDefault={getinfo}>
      
    <div class="parent" id="parent">         
    </div>        
 
    <button type="submit">SAVE</button>
</form>

What am I doing wrong?


Solution

  • Svelte will remove unused styles. In this case the styles aren't used by Svelte and are effectively for a nested pure js component. If you make them global Svelte will not remove them.

    <style>
      /* to create a bigger input */
      :global(.name) {
          font-size: 16pt;
          height: 50px;
      }
          
      :global(.border) {
          border-style : solid;
      } 
    </style>