views:

176

answers:

2

Is there a way to replace inside the DOM of a page using the replace() in javascript

In the source code I want to replace:

<div class="topbar">Bookmark Us</div>

to

<div class="topbar"><span class="larger-font">Bookmark Us</span></div>

When a Google Chrome extenstion is on the matched website of a URL and it will do the above.

Any page that matches:

http://www.domain.com/support.php

Thanks.

+1  A: 

Don't know about how Chrome triggers its extensions, but I can tell you about page content manipulation.

To wrap all the child content of a topbar div in plain JavaScript:

var topbars= document.getElementsByClassName('topbar');
for (var i= topbars.length; i-->0;) {
    var span= document.createElement('span');
    span.className= 'larger-font';
    while (topbars[i].firstChild)
        span.appendChild(topbars[i].firstChild);
    topbars[i].appendChild(span);
}

(getElementsByClassName is a relatively new API, but Chrome 3 supports it. For each matching element, move all its children into a new span element, and put that span inside the div.)

Or using jQuery, if you don't mind dragging a great big framework in:

$('.topbar').each(function() {
    $(this).contents().wrapAll('<span class="larger-font"></span>');
});

Whilst you can operate on HTML as strings, using something like:

for (var i= topbars.length; i-->0;)
    topbars[i].innerHTML= '<span class="larger-font">'+topbars[i].innerHTML+'</span>';

this should in general be avoided, as you will be serialising and re-parsing the entire node contents of the div, in the process destroying any non-serialisable content like JavaScript references, event listeners and form field values.

bobince
+1 for being a correct answer, and for the `i-->0;` bit in the `for` loop. It's obviously simple, and nice in its suggestion that `i` reaches `0`, yet I've never seen or thought of using a `for` condition clause that way.
Max Shawabkeh
+1  A: 

What you want is a content script. Set it to be triggered on the URL(s) you want in the manifest, then use Bobince's code to actually apply the manipulations.

Max Shawabkeh