1

I'm trying to figure out if there is a way (using JavaScript, or jQuery) to go through an entire HTML file replacing all references to external files and replace all the references to files in other directories with the same named file, but without directory information.

For instance, in the HTML text:

  • scripts/script.js gets replaced with script.js
  • images/big.jpg gets replaced with big.jpg
  • css/style.css gets replaced with style.css

etc.

I guess the references in the CSS files need changing too.

2
  • because i want to save the html locally, and than be able to view the page properly without a connection. creating the same directory structure (especially if external files are on a different domain) is untenable, so I need to 'flatten' the directory structure. Commented Oct 21, 2009 at 20:54
  • 5
    I know that in least Firefox, you can do File -> Save Page As and then choose "Save as type: Web Page, complete" and Firefox will download all of the js/css/img files locally and update the HTML document for you. Otherwise, JavaScript is not the right way to do this. Commented Oct 21, 2009 at 21:24

2 Answers 2

1

The code below is very messy, it would be neat, but I hope you resolve what you need.

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script language="JavaScript">

$(function(){

    $("*", $("#container")).each(function()
    {
        try
        {
            //src
            if ($(this).attr("src"))
                if ($(this).attr("src").lastIndexOf("/")!=-1)
                    $(this).attr("src", $(this).attr("src").substr($(this).attr("src").lastIndexOf("/")+1) );

            //href
            if ($(this).attr("href"))
                if ($(this).attr("rel"))
                    if ($(this).attr("rel")=="stylesheet")
                        if ($(this).attr("href").lastIndexOf("/")!=-1)
                            $(this).attr("href", $(this).attr("href").substr($(this).attr("href").lastIndexOf("/")+1) );
        }
        catch(ex)
        {
            $("#lstError").append("<div>"+ex.description+"</div>");
        }
    });

});

</script>
</head>
<body>

    <div id="lstError"></div>

    <div id="container">
        <!-- your html -->
        <link rel="stylesheet" href="pepe/all.css">
        <img src="lele/bl.png" />
        <img src="lele/b.png" />
    </div>

</body>
</html>
Sign up to request clarification or add additional context in comments.

1 Comment

This is just one way to do what you need @cannyboy. insurance is not a good practice because it generates many 404 errors.
1

What about your browser's Save Page as...?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.