简体   繁体   中英

How to replace an Image with a Div

I have a plugin that generates an ajax loading image, upon clicking the submit button. It's generated by wordpress shortcode and is not directly editable, unless I go into the plugin files and change it. But, that would require me to change it every time the plugin updates, which is not ideal.

I'm hoping, rather, to override the image with some extra code.

Basically, I'd like to replace this:

<img class="ajax-loader" src="/ajax-loader.gif">

With a much better looking css loading bar:

<div class="wrap go"><div class="loader bar"><div class="sfmgreen"></div><div class="dkblue"></div><div class="ltblue"></div><div class="aqua"></div></div> 

Is there any code I can use to override the plugin's image and make the replacement?

There's nothing really available in HTML to automatically override an element in the page. You simply have to find it in the DOM and replace it. This means you have to know when it's present so you can have some sort of trigger to do the replacement.

For example, this will work if immediately after some submit button is clicked, the elements are present.

document.querySelector('#some-submit-btn').addEventListener('click', function() {
  var loaders = document.querySelectorAll('.ajax-loader');
  for (var i = 0; i < loaders.length; i++) {
    var loader = loaders[i];
    var replacement = document.createElement('div');
    replacement.innerHTML = '<div class="wrap go"><div class="loader bar"><div class="sfmgreen"></div><div class="dkblue"></div><div class="ltblue"></div><div class="aqua"></div></div>';
    loader.parentElement.replaceChild(loader, replacement);
  }
});

...but if those loader images aren't there until some time later , you may need to wrap that code with some sort of hack like a setTimeout .

In either case, there may be a flash while you see the old thing before your replacement is present. To work around that, maybe hide it with CSS:

 .ajax-loader {
   display: none;
 }

In summary, there's really only going to be hacky ways to do the substitution; updating the plugin is the cleanest way around this. Maybe you can contribute some custom loader HTML code to the project (if it's open source) to avoid having to update the plugin after every update.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM