Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
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>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!