js dynamically sets the required attribute, js dynamically sets the style of the div

Hello everyone, this article will focus on the dynamic setting of the required attribute in js. Dynamically setting the style of div in js is something that many people want to understand. If you want to understand the dynamic setting of css style in js, you need to understand the following things first.

Reading directory
  • JavaScript dynamically creates tables
    • First example
    • Second example
    • Example analysis
  • Table-related properties and methods
    • 1.1 Table object collection
    • 1.2 Table object methods
    • 1.3 Common properties of Table objects
    • 1.4 TableRow object
      • TableRow object methods
      • TableRow object properties
    • 1.5 TableCell Object
      • TableCell object properties
  • JavaScript implements clicking to display and hide tables
    • Technical solutions
  • JavaScript implements dynamic cloning of a table
    • Technical solutions
  • JavaScript implements dynamic click change of cell color
    • Technical solutions

JavaScript dynamically creates tables

1. Method 1: Write the html code to create the table and assign it to the innerHTML of the div.

2. Method 2: Directly use the created table element methods insertRow and insertCell to implement all operation symbols in Python.

3. Create a table by specifying rows and columns: through looping.

First example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo document</title>
    <style type="text/css">
    </style>
</head>
<body>

<h3>Dynamic creation of table 1</h3>
Number of rows <input type="text" value="5" id="rows">
Number of columns <input type="text" value="5" id="cols">
<input type="button" value="Create Table" onclick="creatTab()">
<div id="div1"></div>

<>
    function creatTab() {
        rows = document.getElementById('rows').value
        cols = document.getElementById('cols').value
        div1 = document.getElementById('div1')
        
        // alert(rows + '\
' + cols)
        var tab = '<table border=1 width=500">'
        for (var i = 0; i < rows; i + + ) {
            tab + = '<tr>'
            for (var j = 0; j < cols; j + + ) {
                tab + = "<td style='background:green'>" + i + j + "</td>"
            }
            tab + = '</tr>'
        }
        tab + = '</table>';
        div1.innerHTML = tab
    }
</>

</body>
</html>

Second example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo document</title>
    <style type="text/css">
    </style>
</head>
<body>

<h3>Dynamic creation of table 1</h3>

Number of rows <input type="text" value="5" id="rows">
Number of columns <input type="text" value="5" id="cols">

<input type="button" value="Create Table" onclick="creatTab()">

<div id="div1"></div>

<>
function creatTab() {
    rows = document.getElementById('rows').value
    cols = document.getElementById('cols').value
    div1 = document.getElementById('div1');

    var ta = div1.getElementsByTagName('table')[0]

    if (ta) {
        ta.parentNode.removeChild(ta)
    }

    var tab = document.createElement("table");
    tab.width = 500;
    tab.border = 2;

    for (var i = 0; i < rows; i + + ) {
        tab.insertRow(i)
        for (var j = 0; j < cols; j + + ) {
            tab.rows[i].insertCell(j).innerHTML = i + '' + j;
            tab.rows[i].cells[j].style.background = 'green'
        }
    }

    document.getElementById("div1").appendChild(tab)

}
</>
</body>
</html>

Example analysis

1. What are the commonly used dynamic attributes of table elements (in js)?

Answer: tab.width=500; tab.border=2;.

2. How to get the first table of a certain div?

Answer: var ta=div1.getElementsByTagName('table')[0].

3. How to remove itself from elements in html?

Answer: Find the parent node first, and then remove the child nodes of the parent node. ta.parentNode.removeChild(ta).

4. insertRow(i) Whose method is this?

Answer: table.

5. Whose attribute is insertCell(j)?

Answer: For row, tab.rows[i].insertCell(j).innerHTML=i + '' + j;.

6. How to access the element of row i and column j in the table?

Answer: tab.rows[i].cells[j].style.background='green'.

7. How to add a table to a div by creating an html statement?

Answer: var tab='

' tab + ='

'; div1.innerHTML=tab.

Table-related properties and methods

1.1 Table object collection

cells[] Returns an array containing all cells in the table.

Syntax: tableObject.cells[]

rows[] Returns an array containing all rows in the table.

The rows collection returns an array of all rows in the table.
The set includes all lines defined in thead, tfoot, and tbody.

tBodies[] Returns an array containing all tbodies in the table.
Note: Not commonly used

1.2 Table object methods

createCaption() creates a caption element for the table.
createTFoot() Creates an empty tFoot element in the table.
createTHead() Creates an empty tHead element in the table.
deleteCaption() Deletes the caption element and its contents from the table.
deleteRow() Delete a row from the table.
deleteTFoot() Delete the tFoot element and its contents from the table.
deleteTHead() Delete the tHead element and its contents from the table.
insertRow() Inserts a new row in the table.

1.3 Common properties of Table objects

frame Sets or returns the outer border of the table.
rules Sets or returns the internal borders (row lines) of the table.
caption A reference to the table’s caption element.
cellPadding Sets or returns the amount of space between the cell content and the cell border.
cellSpacing Sets or returns the amount of space between cells in a table.
summary Sets or returns a description (overview) of the table.
tFoot/tHead Returns the TFoot /tHead object of the table. If the element does not exist, it is null.
border/width/id

1.4 TableRow Object

TableRow object methods

deleteCell() deletes the specified cell in the row
Syntax: tablerowObject.deleteCell(index)

insertCell() inserts an empty td element at the specified position in a row.
tablerowObject.insertCell(index)

Return value: A TableCell object representing the newly created and inserted element.

TableRow object properties

vAlign Sets or returns the vertical alignment of data in a row.
Syntax: tablerowObject.vAlign=top|bottom|middle|baseline

rowIndex returns the row’s position in the table.
Syntax: tablerowObject.rowIndex

Others: align/innerHTML/id…

1.5 TableCell Object

TableCell object properties

abbr Sets or returns an abbreviated version of the contents of the cell.
axis Sets or returns a comma-separated list of related cells.
cellIndex Returns the position of the cell in the cell collection of a row.
colSpan The number of columns the cell spans.
rowSpan Sets or returns the number of rows that a cell can span.
vAlign/width/id/align......

JavaScript implements clicking to display and hide tables

1. Add a click event to the table or elements in the table.

2. Then determine whether the data of the current table is displayed or hidden,

3. Then use the display attribute to display (not none) or hide (the value is none) the data in the table

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Demo document</title>
    <style type="text/css">
    </style>
</head>
<body>

<table id="tab" border="1" width="300">
    <caption>Table name</caption>
    <thead>
        <tr>
            <th colspan="3" onclick="hideTab()">Title 1</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Cell 11</td>
            <td>Cell 12</td>
            <td>Cell 13</td>
        </tr>
        <tr>
            <td>Cell 21</td>
            <td>Cell 22</td>
            <td>Cell 23</td>
        </tr>
        <tr>
            <td>Cell 31</td>
            <td>Cell 32</td>
            <td>Cell 33</td>
        </tr>
    </tbody>
    <tfoot>
        <td>Remarks:</td>
        <td colspan="2"></td>
    </tfoot>
</table>

<>
var isHide = false;
function hideTab() {
    var tab = document.getElementById('tab')
    var rows = tab.rows;
    var len = tab.rows.length;
    // tab.style.display='';
    for (var i = 1; i < len; i + + ) {
        if (isHide) {
            rows[i].style.display = '';
        } else {
            rows[i].style.display = 'none';
        }
    }
    isHide = !isHide
}
</>

</body>
</html>

Technical Answers

1. How to merge table columns into table rows?
Answer: Use the colspan attribute, for example, to merge three cells: colspan="3"

2. How to negate bool type variables in js?
Answer: Give yourself what is not yourself. isHide=!isHide

3. Is the rows attribute in the table an element?
Answer: Yes, for example rows[i].style.display='';

4. How to hide the content of an element?
Answer: Set the display attribute to none

5. How to display an element hidden through the display attribute?
answer:
Remove the attribute none of display. You can remove it by assigning a null value rows[i].style.display='';

6. Is display a style in html?
Answer: Yes, for example: rows[i].style.display='none';

JavaScript implements dynamic cloning of a table

Example description: Copying tables and their contents

Key points of the case: copying table content can be easily achieved through innerHTML

The properties of the table need to be copied separately

Attributes of the table tag used

caption A reference to the table’s caption element.
border/width/id…

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>8.4 Demonstration Document</title>
    <style type="text/css">
    </style>
</head>
<body>

<table id="tab" border="1">
    <caption>Table name</caption>
    <thead>
        <tr>
            <th colspan="3">Title 1</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Cell 11</td>
            <td>Cell 12</td>
            <td>Cell 13</td>
        </tr>
        <tr>
            <td>Cell 21</td>
            <td>Cell 22</td>
            <td>Cell 23</td>
        </tr>
        <tr>
            <td>Cell 31</td>
            <td>Cell 32</td>
            <td>Cell 33</td>
        </tr>
    </tbody>
    <tfoot>
        <td>Remarks:</td>
        <td colspan="2"></td>
    </tfoot>
</table>

<input type="button" value="Copy table" onclick="copytab()">

<>
function copytab() {
    var tab = document.getElementById('tab');
    var cotab = document.createElement('table')
    cotab.innerHTML = tab.innerHTML;
    cotab.border = tab.border;
    cotab.style.marginTop = '20px';
    cotab.caption.innerHTML = 'I copied it'
    document.body.appendChild(cotab)
}
</>
</body>
</html>

Technical Answers

1. How to dynamically create a table?
Answer: Use the createElement method of document, and then add the created DOM table object to the body attribute of the document.

2. How to create a table DOM object through the createElement method of document. What are the parameters of the createElement method?
Answer: var cotab=document.createElement('table') The parameter is 'table'

3. What is the function of appendChild?
Answer: append means appending, and appendChild means attaching a child to an element.

4. Why is the appendChild method needed?
Answer: If the dom tag object created by the createElement method of document is not appended to the entity dom tag, it will not be added to the dom tree at all, and it will be meaningless to create the dom.

5. How to dynamically copy table contents?
Answer: Through the innerHTML attribute of the dom table, cotab.innerHTML=tab.innerHTML;

6. What is the return value of document’s createElement method?
Answer: The return value of the createElement method is the created dom tag object.

7. How to dynamically copy table borders?
Answer: Through the border attribute of the DOM table tag. cotab.border=tab.border;

8. How to dynamically copy table styles?
Answer: Through the style attribute of the dom table tag.

9. What are the common attributes of table tags?
Answer: border, title, etc.

10. How to dynamically modify the title of the table?
Answer: Through the innerHTML attribute of the caption attribute of the table dom object.

JavaScript implements dynamic click change of cell color

1. Traverse all rows of the table through the rows attribute of the table, and then traverse the cells in each row through the cells attribute.

2. During the traversal process, dynamically define a click event for each cell and change the background color of the cell.

Example description: Change the background color of a cell after clicking it, and restore the previous style by clicking it again.

Key points of the case:
Traverse all rows of the table through the rows attribute of the table, and then traverse the cells in each row through the cells attribute.
During the traversal process, dynamically define a click event for each cell and change the background color of the cell.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Form topic</title>
</head>
<body>

<table id="tab" border="1">
    <caption>Table name</caption>
    <thead>
        <tr>
            <th colspan="3">Title 1</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Cell 11</td>
            <td>Cell 12</td>
            <td>Cell 13</td>
        </tr>
        <tr>
            <td>Cell 21</td>
            <td>Cell 22</td>
            <td>Cell 23</td>
        </tr>
        <tr>
            <td>Cell 31</td>
            <td>Cell 32</td>
            <td>Cell 33</td>
        </tr>
    </tbody>
    <tfoot>
        <td>Remarks:</td>
        <td colspan="2"></td>
    </tfoot>
</table>

< type="text/java">
/*
    var tab=document.getElementById('tab') //Get table elements
    var rows=tab.rows; //Return an array containing all rows in the table.
    var rlen=rows.length;
    alert(rlen)
    //var cells=tab.cells;
    //var clen=cells.length //This way of writing will cause errors
    cells=rows[1].cells //Cells in a certain row
    alert(cells.length)
*/

function tabCell() {
    var tab = document.getElementById('tab')
    var rows = tab.rows;
    var rlen = rows.length;
    for (var i = 1; i < rlen; i + + ) { //Traverse all rows
        var cells = rows[i].cells; //Get all cells in this row
        for (var j = 0; j < cells.length; j + + ) {
            //Add click event to each cell
            cells[j].onclick = function () {
                if (this.style.background == '') {
                    this.style.background = randomHexColor();
                } else {
                    this.style.background = ''
                }
            }

        }
    }
}

tabCell()

// Randomly generate hexadecimal colors
function randomHexColor() {
    //Randomly generate hexadecimal colors
    var hex = Math.floor(Math.random() * 16777216).toString(16);
    //Generate hexadecimal numbers within ffffff
    while (hex.length < 6) {
        //while loop determines the number of hex digits. If it is less than 6 digits, add 0 in front to make up to 6 digits.
        hex = '0' + hex;
    }
    return '#' + hex; //Return the hexadecimal color starting with '#'
}
</>

</body>
</html>

Technical Answers

1. How to dynamically add click events to elements?
Answer: cells[j].onclick=function(){function body}.

2. How to dynamically obtain the background attribute of an element?
Answer: if (this.style.background=='').

3. What is the relationship between the rows attribute and the column attribute (or cell attribute cells) of the table?
answer:
Rows contain cells (cells is a property of rows).
var cells=rows[i].cells; //Get all cells in this row.

4. How to dynamically obtain elements?
Answer: var tab=document.getElementById('tab').

5. How to dynamically obtain the DOM object of a certain cell from the table?
answer:
Through the rows attribute of the table, traverse all the rows of the table, and then use the cells attribute to find the cells we need.

6. How to determine whether a tag in js has a background color attribute set?
answer:
Get the DOM object corresponding to the tag, and then determine whether the background attribute of the DOM object’s style is an empty string.

if (this.style.background=='')