Search code examples
phphtmlappendchild

Div stuck in Div when inserted using appendChild PHP


I'm trying to insert a div into a HTML page using a for loop and the appendChild method in PHP. The issue I'm running into is that the first div always ends up stuck inside the second div, which always ends up stuck in the third div and so on and so forth. So how do I end the div at the end of the for loop?

///The PHP Side
// Create an insertion point for the Projects element
$projectInsert = $doc->getElementById("projects");

// Create a project Box
for ($x = $row_cnt; $x > 0; $x--) {

$sql2 = "SELECT * FROM `$prjct` WHERE id=$x";
$result2 = mysqli_query($db,$sql2);
$row2 = mysqli_fetch_array($result2,MYSQLI_ASSOC);

//Insert a project Box
$projectBox = $doc->createElement('div');
$projectBox->setAttribute("class","projectBox");
$project_element_title = $doc->createElement('p', $row2["title"]);
$project_element_description = $doc->createElement('p', $row2["description"]);

$projectInsert->appendChild($projectBox);
$projectInsert->appendChild($project_element_title);
$projectInsert->appendChild($project_element_description);

}



//Here's where it's inserting in the HTML
<div class="projectBar" id="projectsBar">
<h4 style="height: 30%; width: 100%; margin: auto;">Projects</h4>
<p id="projects"></p>
</div>

Here's photos of what's happening vs what I want to happen

https://docs.google.com/presentation/d/1OgthPueXHzGXyUi6L3DmgWTtOr6gHpfj8LgGh5OG85Y/edit?usp=sharing

Since I'm new I can't embed images.

Thanks for any and all help!


Solution

  • Instead of appending childs($project_element_title and $project_element_description) to parent($projectBox) you are appending it to super-parent($projectInsert), that's the problem.

    So change:

     $projectInsert->appendChild($project_element_title);
     $projectInsert->appendChild($project_element_description);
    

    To

     $projectBox->appendChild($project_element_title);
     $projectBox->appendChild($project_element_description);