Home better definition of dom elements in vanilla javascript
Reply: 2

better definition of dom elements in vanilla javascript

Nick97
1#
Nick97 Published in 2017-09-14 09:55:38Z

I'd like to know if there's a smoother way create this DOM block dynamically:

<tr>
     <td>text</td>
     <td><input type="checkbox"></td>
</tr>

This function allows me to add a nested tr to my tbody:

 function create_row() {
            var row = document.createElement("TR");
            var cell1 = document.createElement("TD");
            var cell2 = document.createElement("TD");
            var checkbox = document.createElement("INPUT");
            var text = document.createTextNode(extract_textarea());

            checkbox.type = "checkbox";

            cell1.appendChild(text);
            cell2.appendChild(checkbox);
            row.appendChild(cell1);
            row.appendChild(cell2);

            return row;
        }

P.S. I'm new to Javascript so every single tip is appreciated, thanks!

Thijs
2#
Thijs Reply to 2017-09-14 10:13:22Z

You can use innerHTML on a created div to get the HTML elements you want.

function createRow() {
  const
    div = document.createElement('div');
  div.innerHTML = '<tr><td>text</td><td><input type="checkbox"></td></tr>';
  
  return div.firstElementChild
}

const 
  newRow = createRow(),
  tbody = document.getElementById('tbody');
  
tbody.appendChild(newRow);
<table>
  <tbody id="tbody">
  </tbody>
</table>

Young Kyun Jin
3#
Young Kyun Jin Reply to 2017-09-14 10:01:14Z
function create_row() {
   //var row = document.createElement("TR");
   var row = document.createElement("tr");

   //var cell1 = document.createElement("TD");
   //var cell2 = document.createElement("TD");

   //var checkbox = document.createElement("INPUT");
   //var text = document.createTextNode(extract_textarea());

   //checkbox.type = "checkbox";

   //cell1.appendChild(text);
   //cell2.appendChild(checkbox);

   //row.appendChild(cell1);
   row.appendChild(`<td>${extract_textarea()}</td>`);
   //row.appendChild(cell2);
   row.appendChild(`<td><input type="checkbox" /></td>`);


   return row;
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.307749 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO