Question

Assume I have 4 “th” elements on the page and on click of the button I need to create another “th” element but with specific position. For example if it’s 1997 it’ll be created in between 1995 and 2000 elements, and so on.

<table>
<tr>
    <th>1990</th>
    <th>1995</th>
    <th>2000</th>
    <th>2005</th>
</tr>
......

This is the code I have, but it creates new “th” at the very end.

 var tblHeadObj = document.getElementById('<%=Me.GridView1.ClientID %>'); //table head
 var newTH = tblHeadObj.rows[0].appendChild(document.createElement("th"))
Was it helpful?

Solution

LIVE DEMO

var doc = document,
    ROW = doc.querySelectorAll("#myTable tr")[0],
    BUTTON = doc.querySelector("#submit"),
    INPUT = doc.querySelector("#setYear");    

function isNumber(n) { // http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function createYear(){      
  var VAL = parseInt(INPUT.value, 10);         // GET INPUT VALUE
  var TH = ROW.querySelectorAll("th");
  if(isNumber(VAL)){                           // MAKE SURE IT?S A NUMBER
    for(var i=0; i<TH.length; i++){            // LOOP TH ELEMENTS
      var y = parseInt( TH[i].innerHTML, 10 ); // GET YEAR
      if(y>VAL){                               // ONLY IF y>VAL
        var newTH = doc.createElement("th");   // CREATE NEW TH
        newTH.innerHTML = VAL;                 // INSERT VALUE INTO TH
        ROW.insertBefore( newTH, TH[i]);       // https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore
        break;
      }  
    }
  }else{
    alert("PLEASE ENTER A YEAR"); 
  }      
}

BUTTON.addEventListener('click', createYear); // BUTTON CLICK

OTHER TIPS

To insert html after the nth element using jquery:

$("th:eq(1)").after("<th>1997</th>");

...where 1 is your nth element.

check this out. you could use insertBefore()

https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top