[RESOLVED]add Image to a div using Javascript

I need to insert an image to a div  in javascript,but it doesnt work . i have the follwoing code

x = $(‘<div id="’ + id + ‘">’).appendTo($(‘#text’));

x.innerHTML = "<img src=’../../App_Themes/Images/add_btn.png’ />"

or there is any way to add an image to a div in javascript providing that i have the image path like this:

http://localhost/myProject/App_Themes/Images/image.jpg

Hi,

Try like this:

x = $('<div id="' + id + '">');

x.html("<img src='../../App_Themes/Images/add_btn.png' />");

x.appendTo($('#text'));

Hi Sanfoor,

According to your requirements, I made a test on my computer, adding image, when page loads.

For achieving your goal, please try my code as below,

<script type="text/javascript">
        onload = function f()
        { document.getElementById("insert").innerHTML = '<img src="../Image/bg.jpg"/>'; }//change the address into your image
    </script>
<body>
    <form id="form1" runat="server">
    <div id="insert">   
    </div>
</form>

This function is adding image into div by the id of div.

Hope this can help you.

Best regards,

Try change
hope this help
x.innerHTML = "<img src=’../App_Themes/Images/add_btn.png’ />"

Hi Sanfoor,

Thanks for your post.

As for your problem, you could refer to my below sample.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style>
        .addimg{
            display:block;
            width:600px;
            height:165px;
            float:left;
            background-image:url(' ../../App_Themes/Images/add_btn.png');
        }
    </style>
    <script src="../../Scripts/jquery-1.8.2.js"></script>
    <script>
        $(function () {
            //add <img> tag in div
            $("#imgc").html("<img src=' ../../App_Themes/Images/add_btn.png ' />");

            //or set image as backgroung image, in this way, you should set appropriate height and width to div
            $("#imgc1").addClass("addimg");
        })
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div id="imgc"></div>
            <br />
            <div id="imgc1"></div>
        </div>
    </form>
</body>
</html>

If you have any question about this issue, please post back.

Best Regards,

Fei Han

Leave a Reply