Ecommerce Optimizer
Ecommerce Optimizer

Reputation: 15

replace src element with javascript

I am creating a simple coontent builder for a project. When someone clicks an image, a dialoge box opens and asks them to input the url to replace the src, to input a new alt, and to imput a new title It should replace each of those elements iin the following img tag

Before:

<div class="three">
    <!-- 1 Image -->
    <img id="imageid" src="https://cdn.shopify.com/s/files/1/0645/1401/files/Wellness_700x.png" class="lazyload--fade-in lazyautosizes lazyloaded" alt="" title="" data-iml="333">
</div>`

Results:

<div class="three">https://storage.googleapis.com/support-kms-prod/RrjdySjRxcYJL3NpcXaobwTxuk7zctDbL8rX</div>

The Code

$('.main').on('click', '.element',function(e){
  console.log('Delete Element? ', isDelete(e,this));
  currentSelected = e.target;
  if(!isDelete(e,this)) {
    if(e.target.tagName == "IMG") {
      let imgUrl = prompt('Enter URL Here');
      let imgAlt = prompt('Enter Alt Text Here');
      let imgTitle = prompt('Enter Title Here');
      e.target.parentNode.innerHTML = imgUrl.replace('src=');e.target.parentNode.innerHTML = imgAlt.replace('alt=');
      e.target.parentNode.innerHTML = imgTitle.replace('title=');
    } else if (['h2', 'h3', 'h4', 'h5', 'h6', 'a','p', 'li', 'iframe'].includes(e.target.localName)) {
      if(e.target.localName == 'a') {
        e.target.innerText = prompt('Enter Call To Action Text') + " →";
      } else {
        e.target.innerText = prompt('Enter Heading Text Here');
      }
    }
  } else {
    e.target.remove();
  }
  const code = $('.main__layout-content')[0].outerHTML.replace(/"/g, `'`).split('\n').join('');
  setCookie("code", code, 10);

Upvotes: 0

Views: 71

Answers (1)

Peterrabbit
Peterrabbit

Reputation: 2247

If you have to replace any attribute value on an html element just do it the simple way:

// once you have checked that the event target is the img elmt you want...
const img_elmt = e.target;
e.target.src = some_url;

Upvotes: 1

Related Questions