I have the following code that inserts a table into a div using insertBefore, but I'm struggling to get the positioning of the table correct:
//function creates standard HTML table
const table = createTable({ data, propertyId });
let wrapper = document.querySelector(classes.propertySummary);
wrapper.insertBefore(table, wrapper.children[1]);
Produces the following in the DOM:
<div >
<div>Where my table should sit inside</div>
<table></table>
<div></div>
</div>
Can anyone help?
CodePudding user response:
wrapper.children[1] returns the second DIV inside <div >. insertBefore() inserts an element inside the element that calls insertBefore(), in this case wrapper which returns <div >. The second parameter provided to insertBefore() determines the place among, and alongside, the list of children the first parameter is placed.
The TABLE is inserted before the second DIV .children[1], positioning the TABLE after the first DIV, not inside the first DIV.
To get there dig just a bit deeper. Here's one way:
let wrapper = document.querySelector(classes.propertySummary " div");
Appending " div" to the querySelector(), returns ".summary div". This selects the first DIV inside <div >.
Outputs:
<div >
<div>
Where my table should sit inside
<table></table>
</div>
<div></div>
</div>
Be sure classes.propertySummary returns ".summary"—notice the preceding dot. If not, use "." classes.propertySummary " div" for the querySelector() parameter.
const classes = {"propertySummary": ".summary"}, data = "", propertyId = "";
function createTable (obj) {
return document.createElement("table");
}
//function creates standard HTML table
const table = createTable({ data, propertyId });
let wrapper = document.querySelector(classes.propertySummary " div");
wrapper.insertBefore(table, wrapper.children[1]);
<div >
<div>Where my table should sit inside</div>
<div></div>
</div>
wrapper.insertBefore(table, wrapper.children[1]);
...is superfluous. appendChild():
wrapper.appendChild(table);
...produces the same result.
