user2077098
user2077098

Reputation:

Replace img tag with H1 tag

I am working on a simple GreaseMonkey script. I don't have access to use jQuery.

I need to replace this HTML:

<img border="0" title="NEW_UNI_LOGO.png" src="/OA_MEDIA/NEW_UNI_LOGO.png"></img>

With this HTML:

<h1>Production</h1>

I have tried:

var cells = document.querySelectorAll('body');
for (var i = 0; i < cells.length; i++) {
        john = cells[i].innerHTML;
        john = john.replace('<img border="0" title="NEW_UNI_LOGO.png" src="/OA_MEDIA/NEW_UNI_LOGO.png"></img>', '<h1>Production</h1>');
        cells[i].innerHTML = john;
}

But unfortunately it doesn't work.

The HTML for the img tag is placed inside a table. The HTML snippet I'm trying to replace only appears once on the page.

Thanks

Upvotes: 1

Views: 375

Answers (2)

leoinfo
leoinfo

Reputation: 8215

Try this:

var imgs=document.getElementsByTagName('img');
for(var i=imgs.length-1;i>=0;i--){
    if(imgs[i].title == 'NEW_UNI_LOGO.png') {
      var h1 = document.createElement('h1');
      h1.innerHTML = 'Production';
      imgs[i].parentNode.insertBefore( h1, imgs[i] );
      imgs[i].parentNode.removeChild(imgs[i]);  
    }
}

Here is the code working: http://jsfiddle.net/4UHHL/

Or, you can check the image file name like this:

var img_file_name = 'NEW_UNI_LOGO.png'
var imgs=document.getElementsByTagName('img');
for(var i=imgs.length-1;i>=0;i--){
    if(imgs[i].src.toLowerCase().indexOf('/'+img_file_name.toLowerCase())!=-1) {
      var h1 = document.createElement('h1');
      h1.innerHTML = 'Production';
      imgs[i].parentNode.insertBefore( h1, imgs[i] );
      imgs[i].parentNode.removeChild(imgs[i]);  
    }
}

Here is the code for this second part: http://jsfiddle.net/Wh2q3/

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324790

Try:

var img = document.querySelector("img[title='NEW_UNI_LOGO.png']");
var h1 = document.createElement('h1');
h1.appendChild(document.createTextNode("Production");
img.parentNode.replaceChild(h1,img);

This seeks out the specific image element (using the title as an identifier - adjust if needed), and replaces it with a freshly created H1 element.

Upvotes: 2

Related Questions