1. Get dom elements

<div class="exchange" id="box">1<p></p></div>
<div>2</div>
Copy the code
document.getElementTagName;// Get the label
//console.log(document.getElementsByTagName("div")) 

document.getElementsByClassName// Get the class name
// console.log(document.getElementsByClassName("exchange"));

document.getElementById/ / to get id
//console.log(document.getElementById("box"))

document.querySelector// Get the first element that satisfies the condition
//console.log(document.querySelector("#box"))
//console.log(document.querySelector(".exchange p"))

document.querySelectorAll// Get multiple elements that meet the criteria
/ / the console. The log (document. QuerySelector (" div ")) / / multiple
Copy the code

2. Manipulate elements

Generate TR and TD through a loop

  <div class="exchange" id="box">1 </div>
Copy the code
var trStr="";
for(var i=0; i<3; i++){// Generate td string through loop
    var tdStr = "";
    for (var j = 0; j < 3; j++) {
            tdStr += " 
      ";
        }
        // console.log(tdStr);
        // Determine the odd or even number of rows
        if(i%2= =0){
            trStr+="<tr style='background:blue'>"+tdStr+"</tr>";// Even lines add background color
        }else{
            trStr+="<tr>"+tdStr+"</tr>";// Add background color to odd lines}}var tableStr="<table border='1'>"+trStr+"</table>";//生成table
var divEle = document.querySelector(".exchange");//获取div
divEle.innerHTML=tableStr;

Copy the code

3 Create a DOM element

document.createElement("p")// Create the element
p.innerHTML = "I am P content";
// Note that the innerHTML needs to receive a string

//appendChild adds the object to the specified location
var liEle=document.createElement("li")/ / create the li
var pEle=document.createElement("p")/ / create a p
liEle.appendChild(pEle);
  • InnerHTML needs the string appendChild needs the object // 2. InnerHTML replaces HTML appendChild appends HTML Copy the code

    Create a table with elements

    var tableEle = document.createElement("table");// All you need to create a table is a label name
    // Create tr through a loop and add it to tableEle once it's done
    for(var i=0; i<3; i++){var trEle = document.createElement("tr");
                if(i%2= =0) {// Add a background color to the tr created at even positions;
                    trEle.style.backgroundColor = "blue";
                }
                // Each line of tr creates 3 TDS for a total of 9 TDS
    
                for(var j=0; j<3; j++){// Add content to TD
                        var tdEle = document.createElement("td");
                    td1.innerText = "Content";
                    trEle.appendChild(tdEle);
                }
    tableEle.appendChild(trEle); // appendChild is appended
     }
    console.log(tableEle);
            // Put the table in the body
    document.body.appendChild(tableEle);
    
    
    
    Copy the code