View Full Version : Finding specific HTML and replacing it

06-11-2010, 11:31 AM
I'm a bit of a Javascript noob, so please bear with me!

I'm trying to create a piece of code that will check a webpage and replace any instances of a specific line of HTML with another line of HTML.

The code I have so far doesn't work, but I have a feeling that's down to my awful Javascript skills!

For example, in the following code I'd want to replace all instances of <li><a href="index.pdf">Index</a></li> with <li><a href="contents.pdf">Contents</a></li>

<div id="downloads">
<p>Please click on your downloads below:</p>
<li><a href="index.pdf">Index</a></li>
<li><a href="chapter1.pdf">Chapter 1</a></li>
<li><a href="chapter2.pdf">Chapter 2</a></li>
<li><a href="chapter3.pdf">Chapter 3</a></li>
<li><a href="credits.pdf">Credits</a></li>

The Javascript I have so far is:

<script type="text/javascript">

var aEls = document.getElementsByTagName('a');
for (var i = 0, aEl; aEl = aEls[i]; i++) {
aEl.href = aEl.href.replace('index.pdf','contents.pdf');


Obviously this is meant to just replaces the a href elements, but I got a bit stuck after this!

Any pointers would be much appriciated.

06-11-2010, 12:32 PM
Obviously this is meant to just replaces the a href elements, but I got a bit stuck after this! What if there's an item like

<li><a href="foo.pdf">Index</a></li>

You might need something like

var aEls = document.getElementById('downloads').getElementsByTagName('a');
for (var i = 0; i<aEls.length; i++) {
aEls[i].href = aEls[i].href.replace('index.pdf','contents.pdf');


06-11-2010, 12:38 PM
Actually, I've just realised what I need is slightly different to my original post.

The page this code will go on dynamically generates a number of pieces of text based on the user's answers to a survey, which I want to then replace with an appropriate pdf download.

So the page will generate something like:

<div id="downloads">
<p>You expressed an interesting in the following chapters. Please click on your downloads below:</p>
<li><p>Chapter 2</p></li>
<li><p>Chapter 3</p></li>

And I want the page to automatically replace the chapters with the appropriate <a href="index.pdf>Index</a> for example.

Hope that's clear!