Skip to content
Advertisement

How can I create an img element when pressing a button with JavaScript?

When I click I want an img tag to be generated and with an image I have tried several ways but it doesn’t work.

var oferr=document.getElementsByClassName("a")[0];
var new=document.getElementsByClassName("create")

oferr.addEventListener('click', function () {
    let new_element=document.createElement('img');
    let image=document.createAttribute('src','img/imagen_1');

    new_element.appendChild(imagen); 
    new.appendChild(new_element);
}) 
    <div class="ad">
        <h1>10% discount</h1>
    </div>
    <header>
        <div class="logo">
            <h2 class="name">Environments</h2>
        </div>
        <nav>
            <a href="" class="nav-link">Offers</a>
            <a href="" class="nav-link">Products</a>
            <a href="" class="nav-link">Login</a>
        </nav>
    </header>

    <div id="create">

    </div>
    <script src="/js/main.js"></script>

Advertisement

Answer

Just set the image’s .src property to the source URL.

create is an ID, not a class, so use document.getElementById().

The anchors don’t have class="a", you should use document.getElementsByClassName("nav-link").

You need to use Event.preventDefault() in the event listener to prevent following the links.

You can’t use new as a variable name because it’s a reserved keyword.

var oferr=document.getElementsByClassName("nav-link")[0];
var create=document.getElementById("create")

oferr.addEventListener('click', function (e) {
    e.preventDefault();
    let new_element=document.createElement('img');
    new_element.src = 'img/imagen_1';

    create.appendChild(new_element);
})
<div class="ad">
        <h1>10% discount</h1>
    </div>
    <header>
        <div class="logo">
            <h2 class="name">Environments</h2>
        </div>
        <nav>
            <a href="" class="nav-link">Offers</a>
            <a href="" class="nav-link">Products</a>
            <a href="" class="nav-link">Login</a>
        </nav>
    </header>

    <div id="create">

    </div>
    <script src="/js/main.js"></script>
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement