Ivan Z.
Ivan Z.

Reputation: 37

How do I insert an image into HTML with Javascript

I'd like to make an img visible but not with the tag but Javascript.How can I make the function work somehow?

<!DOCTYPE html>
  <html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>PingPongKép</title>
    <link rel="stylesheet" href="CSS/style.css">
  </head>
<body> 
 <script>
     function ilonaKep(){
       var ilona = document.createElement ("IMG");
       x.setAttribute ("src", "img/ilona.jpg");
     }     
    </script>
    <p>Let's See the image</p>
    <script>
      ilonaKep();
    </script>
   </p>
</body>
</html>

Upvotes: 1

Views: 6497

Answers (2)

zer00ne
zer00ne

Reputation: 43861

Update

OP needs a way to style images. See Demo 3


The function was missing:

  1. A target element to place the img
    • Added a <figure> to the layout
    • Reference target: var frame = document.querySelector('.frame');
  2. Once an element is created, it must be added to the DOM
    • frame.appendChild(ilona);

See Demo 1


An alternative way to adding an image programmatically to the DOM is by using a method or property that takes a given string and parses it into HTML like innerHTML or insertAdjacentHTML(). Demo 2 uses insertAdjacentHTML() and Template Literal.


Demo 1

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>PingPongKép</title>

</head>

<body>

  <figure class='frame'>
    <figcaption>Image 1</figcaption>
  </figure>




  <script>
    function ilonaKep() {
      var frame = document.querySelector('.frame');
      var ilona = document.createElement("IMG");
      ilona.src = "http://p1.vatera.hu/photos/52/52/b859_4_big.jpg?v2";
      ilona.width = "300";
      frame.appendChild(ilona);
    }

    ilonaKep()
  </script>
</body>

</html>

Demo 2

// Reference the target element
var frame = document.getElementsByClassName('frame')[0];

// Efficient use of a string. Ref: Template Literal
var string = `<img src="http://www.nemzetisport.hu/data/cikk/2/12/81/9/cikk_2128109/ping2.jpg">`;

/* insertAdjacentHTML() will parse a string into HTML
|| and insert it in/out/before/after/as the first/last
|| child of the target element. Ref: insertAdjacentHTML()
*/
frame.insertAdjacentHTML('beforeend', string);
<figure class='frame'>
  <figcaption>Image 2</figcaption>

</figure>

Demo 3

// Reference the target element
var frame = document.getElementsByClassName('frame')[0];

// Efficient use of a string. Ref: Template Literal
var string = `<img src="http://www.nemzetisport.hu/data/cikk/2/12/81/9/cikk_2128109/ping2.jpg">`;

/* insertAdjacentHTML() will parse a string into
|| HTML and insert it in/out/before/after/as the
|| first/last child of the target element. Ref:
|| insertAdjacentHTML()
*/
frame.insertAdjacentHTML('beforeend', string);


/*~~~~~~~~~~~~~~[Styling]~~~~~~~~~~~~~~~~~*/

/* Get reference to target by Document Image 
|| Collection. The following statement will
|| retrieve the first <img> on the page
*/

var img = document.images[0];

/*A. Inline Style Attribute
    /| Signature
    \| obj.style.propertyName = 'value';
    ====================================
    This is not rcommended yet it's the most
    direct and simple way to style a node
    */

img.style.border = '3px dashed red';

/*B. By CSS Selector
    /| Direct Selectors
    || #id, tagName, [attribute], or .class
    == ====================================
    || Indirect Combinators or Inheritance
    || descendant [space] or >
    || sibling ~ or +
    This is the perfered way in particular, the
    .class selector is universally recommended
    
   */
/* classList method allows us to manipulate
    || an element's classes. Add the class to the
    || <style> block or stylesheet (style.css)
    */

img.classList.add('enlarge');

/*C. By modifying the stylesheet CSS.
    /| Signature
    \| var css = document.styleSheets[0].rules[0].style;
    |/ css.setProperty('property', 'value');
    ===========================================
    To target the first stylesheet snd its first rule
    ===
    This is a very uncommon procedure and its 
    complexity far outweighs its usefulness. Also,
    this won't work here because this stack is sandboxed 
    like a beach. This example is disabled so it doesn't 
    disrupt the other working examples.
    

var css = document.stylesheets[0].rules[0].style
cs.setProperty('transform', 'scale(.5,.5)');
*/
.enlarge {
  transform: scale(1.2, 1.2)
}
<figure class='frame'>
  <figcaption>Image 2</figcaption>

</figure>

Upvotes: 1

geekonaut
geekonaut

Reputation: 5954

You need to append the image to the DOM:

 function ilonaKep(){
   var x = document.createElement ("IMG");
   x.setAttribute ("src", "img/ilona.jpg");
   document.body.appendChild(x);
 }

While we're at it, you can do it using the ImageElement constructor:

function ilonaKep() {
  var img = new Image();
  img.src = 'img/ilona.jpg';
  document.body.appendChild(img);
}

Upvotes: 1

Related Questions