Inserting an image tag into a container using JavaScript

I am currently struggling to use JavaScript to insert an image into the placehere div. Could someone please assist me in troubleshooting my code?

<html>
<script type="text/javascript">
var elem = document.createElement("img");
elem.setAttribute("src", "images/sunflower.jpg");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Sunflower");
document.getElementById("placehere").appendChild("elem");
</script>
<body>

<div id="placehere">

</div>

</body>
</html>

Answer №1

Implement the following code to insert an element into the document with id "placehere":

Do not use the following code:

document.getElementById("placehere").appendChild("elem");

Instead, set the source using the code snippet below:

elem.src = 'images/hydrangeas.jpg';

Answer №2

It is important to place your div before your javascript code. This ensures that the javascript executes only after the div exists. Otherwise, you may encounter errors where the div cannot be found or the appendChild method is called on null. Here is an example of how your code should be structured:

window.onload = function() {
  var elem = document.createElement("img");
  elem.setAttribute("src", "http://img.zohostatic.com/discussions/v1/images/defaultPhoto.png");
  elem.setAttribute("height", "768");
  elem.setAttribute("width", "1024");
  elem.setAttribute("alt", "Flower");
  document.getElementById("placehere").appendChild(elem);
}
<div id="placehere"></div>

To demonstrate this concept, you can view this example with the onload event and this example without the onload event. By opening the console, you will notice the difference in behavior based on the placement of the div.

Answer №3

function addImage()
{
    //dynamically insert an image and define its properties
    var newImg = document.createElement("img");
    newImg.src = "image.jpg";
    newImg.id = "myImage";
    var container = document.getElementById("imageContainer");
    container.appendChild(newImg);
}

<span id="imageContainer">&nbsp;</span>

Answer №4

This alternative solution offers a more concise way to achieve the same result:

<div id="picDiv"></div>

Using JavaScript:

document.getElementById('picDiv').innerHTML = '<img width="100" height="100" src="pictures/sunflower.jpg">';

Answer №5

If you're curious about how to achieve this using JQuery:

$("<img height='200' width='200' alt='testImage' src='https://avatars.githubusercontent.com/u/47340995?v=4'> </img>").appendTo("#container");

Reference: https://api.jquery.com/jQuery/#jQuery2

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How come I'm encountering issues when trying to click on the "register-selection" button in my Bootstrap and JS setup?

I am facing a challenge while developing my website. I want to trigger an alert when the "register-selection" is clicked, but despite trying both Jquery and vanilla Javascript, I have not been successful. Even after searching online resources and ChatGPT f ...

Adjust the overall cost according to the quantity using jQuery or JavaScript

I'm currently working on a project that involves input fields for Product Price, Quantity Form Field, and displaying the Total price. My goal is to have the Total price automatically update based on the product price and quantity with jQuery. I am loo ...

What is the most effective way to transfer information between two pages in React JS?

I am a newcomer to react and currently working on a project that involves two pages/components. I collect user details on one page and need to display that data on another page. However, I am facing difficulties in achieving this. Can someone please provid ...

Leveraging JavaScript Functionality with ASP.NET Identity Roles

I'm currently working on an application that utilizes JQuery DataTables. The goal is to have these tables visible to all users, but restrict the click functionality to a specific user role. One way I can achieve this is by setting up authorization on ...

Curious as to why body.scrollTop functions differently in Google Chrome and Firefox compared to Microsoft Edge

Up until recently, the code body.scrollTop was functioning correctly in my Chrome browser. However, I've noticed that now it is returning 0 in both Firefox and Chrome, but still giving the proper value in Microsoft Edge. Is there anyone who can assis ...

Can you explain the concept of 'each' when using the looping method in jQuery?

I'm grappling with accessing data within a table row. The data could be within a <td> tag, as text in an input field, or as a checkbox in an input field, or even as a button. To illustrate, here's a snippet of a small table: <table bor ...

Incorporate data into the div element

I've been attempting to populate a div after selecting 3 different options from select boxes, but nothing seems to be happening. I have confirmed that the PHP function works as expected when tested manually, but I'm unable to get it to populate a ...

Encountering a CORS header issue while working with the Authorization header

Here is the code snippet I am currently working with: https://i.stack.imgur.com/DYnny.png Removing the Authorization header from the headers results in a successful request and response. However, including the Authorization header leads to an error. http ...

When dynamically adding an option, the select value becomes empty

I am facing a problem with a select element that I cannot change programmatically. Initially, the select has only one option: The initial HTML structure looks like this: <select id="clients" name="client"> <option>Existing Clients...</ ...

Javascript clock problem, kick off on click

Currently working on a game and in need of a counter that starts when clicked and stops at 00 (From 1m to 00). It is currently starting onload and cycles back to start when it reaches 00. HTML: <body> <div> <div class="timer" >Battle t ...

Node.js and the Eternal Duo: Forever and Forever-Montior

Currently, I am utilizing forever-monitor to launch a basic HTTP Node Server. However, upon executing the JavaScript code that triggers the forever-monitor scripts, they do not run in the background. As a result, when I end the TTY session, the HTTP server ...

Are there problems with the response values of functions that can handle varying object interfaces?

Currently in the process of developing a command line blackjack app with Node and Typescript, even though I am relatively new to Typescript. My main challenge lies in implementing interfaces for player and dealer objects, as well as creating functions that ...

Tips for adding CSS attributes to a <style> tag in Internet Explorer

My current issue involves an ajax web application that loads all parts on a single page, specifically index.html. The inner parts being loaded in index.html have exceeded 32 pages (html, js, css). Now I am facing difficulties with the CSS files that need ...

What is the best way to display these images correctly within a slider?

My goal is to display 4 images/company logos per slide, but they all end up clustered on one slide. Despite my efforts to adjust the CSS, nothing seems to work. This is what my code currently renders: https://i.sstatic.net/ThaOK.png Here are the react co ...

Function "Contains" not Present in Object

Upon executing the code provided below, I encounter the following error message. An issue has arisen: Cannot find function contains in object Is Patient Fasting?/# of Hours->Yes; 12 hours. Here is the snippet of my code: var i = 0; var tempF ...

Having trouble adding HTML content to a parent div using jQuery and BackboneJS?

Utilizing Backbone Marionette to create a series of views, I am now faced with the task of making an AJAX call to my backend. In order to provide visual feedback to the user indicating that an action is being performed, I decided to integrate a spinner int ...

Use Javascript or Jquery to dynamically change the background color of cells in HTML tables based on their numerical

I am working with a collection of HTML tables that contain numbers presented in a specific style: <table border="1"> <tr> <th>Day</th> <th>Time</th> <th>A</th> <th>B</th> &l ...

Conceal the overflow from absolutely positioned elements

I've gone through all the similar examples but still struggling to find the correct solution. My issue involves a basic Side Menu that toggles upon button click. Within the menu, there is a list of checkboxes positioned absolutely with the parent con ...

Create a page turning effect in React that simulates scrolling a certain amount at a time

Is there a way to disable default scrolling and have the page automatically scroll to the next item? For example, if I have element2 below element1, how can I set it up so that when I scroll down once, the page scrolls directly to the position of element2 ...

I'm unsure about the JavaScript toolkit framework's handling of selecting HTML class attributes

I have been exploring the Electron Framework using a JavaScript toolkit known as Xel. In my main.js file, I am working with the following syntax: document.querySelector("menu.selected").className.remove('selected') In my Xel code snippet, I hav ...