How to find/replace html with javascript?

I'm looking for a javascript solution to find all jQuery scripts on a html page and replace the code with the latest version of jQuery.

Original line:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

Replace with:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>

Answers


var all = document.querySelectorAll('script[src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"]'),
script;
for(var i=0, len = all.length; i < len; i++){
    script = all[i].cloneNode(false);
    script.src = "http://code.jquery.com/jquery-1.7.1.js";
    document.body.removeChild(all[i]);
    document.body.appendChild(script);
}

That works for me. You can see it in this demo, but you'll have to type the command $.fn.jquery in the console to see that the version has actually changed.


Most of the examples people are writing DON'T WORK! (Examples have been removed.) jQuery().jquery returns the jQuery version:

$("script[src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js']")
    .attr("src","http://code.jquery.com/jquery-1.7.1.js");
console.log(jQuery().jquery);

This writes 1.3.2 to the console. Just changing the src of a script doesn't make the new script actually run! Even if you give the new script chance to load with a setTimeout or load event, it still won't change the version.

You could load the script as an AJAX query and eval it.

jQuery.getScript("http://code.jquery.com/jquery-1.7.1.js");

But even that might not produce the result you expect. Any reference to jQuery or $ further down the page will have already pointed to the old jQuery object (version 1.3.2), not the new one. So to use 1.7.2, you'd then have to eval all your scripts only after getting and evaling the new script. So you're gonna have to find another way I'm afraid.

Edit: I suppose you could do this:

jQuery.getScript("http://code.jquery.com/jquery-1.7.1.js", function () {
    // Only after jQuery has run
    jQuery.getScript('my-script-which-depends-on-1.7.js');
});

but it's a bit cumbersome.


Need Your Help

Can I identify intranet page content using Named Entity Recognition?

nlp nltk

I am new to Natural Language Processing and I want to learn more by creating a simple project. NLTK was suggested to be popular in NLP so I will use it in my project.

What is wrong with polling?

c# .net asp.net polling

I have heard a few developers recently say that they are simply polling stuff (databases, files, etc.) to determine when something has changed and then run a task, such as an import.