HTML DOM

by isogunro

HTML

<div>
    <p class='mainPara'>Main Paragraph</p>
    <ul id="myList">
        <li>First List Item</li>
        <li>Second List Item</li>
        <li>Third List Item</li>
        <li>Fourth List Item</li>
        <li>Fifth List Item</li>                
    </ul>
    <div id="innerDiv">
        <p class='subpara' id='p1'></p>
        <p class='subpara' id='p2'></p>
        <p class='subpara' id='p3'></p>
        <p class='subpara' id='p4'></p>
        <p class='subpara' id='p5'></p>        
    </div>
    <table id="myTbl" border="1">
        <tr>
            <td>Row 1</td>
            <td>Row 1</td>            
        </tr>
        <tr>
            <td>Row 2</td>
            <td>Row 2</td>            
        </tr>
        <tr>
            <td>Row 3</td>
            <td>Row 3</td>            
        </tr>        
        <tr>
            <td>Row 4</td>
            <td>Row 4</td>            
        </tr>        
        <tr>
            <td>Row 5</td>
            <td>Row 5</td>            
        </tr>                
    </table>
    <input type="text" /><input type="submit" value="Submit" />
</div>

CSS

#myTR {
    font-weight:bold;
    color:red;
}

#myLI {
    font-weight:bold;
    color:blue;
}

#liID {
    font-weight:bold;
    color:yellow;
}

JavaScript

//Lesson on adding a list item <li>

//Get the id of the element you want to add
var inner = document.getElementById("myList");

//Create the element you want to add
var newLi = document.createElement("li");
newLi.setAttribute("id","liID");
//Add text the new <li> will have
newLi.innerText = "Sixt List Item";
//Append it at the end of UL
inner.appendChild(newLi);

//insertBefore
//need to insert a new li before "First List Item"
var newLIEl = document.createElement("li");
newLIEl.setAttribute("id","myLI");
newLIEl.innerText = "Before LIaa";
var element = inner.insertBefore(newLIEl,inner.firstChild);



//GOAL: To add a row with content in cells to a table

//Grab the table id
var newTbl = document.getElementById("myTbl");
//create table row element
var newTR1 = document.createElement("tr");
newTR1.setAttribute("id","myTR");
var newTD1 = document.createElement("td");

var tdText = document.createTextNode("ROW 6-CELL 1");
newTD1.appendChild(tdText);
newTR1.appendChild(newTD1);

var newTD2 = document.createElement("td");
var tdText2 = document.createTextNode("ROW 6-CELL 2");
newTD2.appendChild(tdText2);
newTR1.appendChild(newTD2);

newTbl.appendChild(newTR1);


//Adding a TH to the table
var newTR_1 = document.createElement("tr");
var newTh_1 = document.createElement("th");
var newThText_1 = document.createTextNode("Header 1");
newTh_1.appendChild(newThText_1);
newTR_1.appendChild(newTh_1);

var newTh_2 = document.createElement("th");
var newThText_2 = document.createTextNode("Header 2");
newTh_2.appendChild(newThText_2);
newTR_1.appendChild(newTh_2);



newTbl.insertBefore(newTR_1, newTbl.firstChild);