Search code examples
javascriptjqueryhtml-listsfill

filling ul li with images


I have problem with ul li fill with

<ul>
     <li></li>
     <li></li>
     <li></li>
     <li></li>
</ul>

I need to put in all li with javascript

but please without this example :

$("ul").html("<li><img src='something' /></li>");

Because i need this ul li before javascript load.

I want after javascript to look like :

<ul>
    <li><img src='something' /></li>
    <li><img src='something' /></li>
    <li><img src='something' /></li>
    <li><img src='something' /></li>
</ul>

My question is : How to fill all ul li with images.

And javascript work with for loop. Because maybe i have this variant :

<ul>
     <li></li>
     <li></li>
     <li></li>
     <li></li>
</ul>

4 li and only 2 image, and to look like this :

<ul>
    <li><img src='something' /></li>
    <li><img src='something' /></li>
    <li></li>
    <li></li>
</ul>

I hope i explain this. Thanks anyway

My php code :

<?php
session_start();
include_once('connect.php');

$path = "../uploads/";
$i = -1;
foreach($_FILES['files']['name'] as $key => $name) {
    $i++;
    $image_info = getimagesize($_FILES['files']['tmp_name'][$key]);
    $image_width = $image_info[0];
    $image_height = $image_info[1];

    if($image_width > $image_height) {
        $height = $image_height;
        $width = $height;
    } else if($image_width < $image_height) {
        $width = $image_width;
        $height = $width;
    } else {
        $width = $image_width;
        $height = $image_height;
    }

    $canvas = imagecreatetruecolor($width, $height);
    $current_image = imagecreatefromjpeg($_FILES['files']['tmp_name'][$key]);

    imagecopy($canvas, $current_image, 0, 0, ($image_width/2)-($width/2), ($image_height/2)-($height/2), $width, $height);
    imagejpeg($canvas, $path.'cropped_'.$name, 100);


    echo 
    "
        <script type='text/javascript'>
            var _img = document.createElement('img');
            _img.src = 'uploads/".$name."';

            $('.image-upload ul li:nth(".$i.")').append(_img);
        </script>
    ";
}

?>

Before : https://i.sstatic.net/vnfZm.png

After https://i.sstatic.net/Ve1CC.png


Solution

  • var _ul=document.getElementByTagName('ul');
    var _list=_ul.getElementsByTagName('li');
    
    for (var i=0;i<=_list.length;i++)
      {
        var _img=document.createElement('img');
        _img.src="something";
        _img.id="foo"+i;
        _list[i].appendChild(_img);
    
      }