Log in

View Full Version : Replacing HTML in a page



Kent
12-14-2006, 08:36 PM
I would like to replace some code on the HTML page when it is loaded.

Like this <div class="class-here-to-replace"> and when the code executes then it will like this <div class="my-class-here">. I would like to specify the exact class to replace. ie. class-here-to-replace.

This is also embedded in an iFrame Tag. I do not know how to do it. Any tips will be fantastico, but the whole code will be fantastico x 12.5


Thankyou

ddadmin
12-14-2006, 10:05 PM
you looking to physically modify the code when the page loads, or via JavaScript to merely manipulate the document's DOM dynamically? BTW this would seem to be a coding question versus "Looking for such a script...", so moving thread.

Twey
12-14-2006, 10:17 PM
In order of advisability:
Use a server-side script to perform the transformation on the fly. Edit your page statically. DOM version:
window.onload = function() {
for(var i = 0, e = document.getElementsByTagName("div"); i < e.length; ++i)
if(e[i].className === "class-here-to-replace")
e[i].className = "my-class-here";
}; innerHTML version:
window.onload = function() {
document.body.innerHTML = document.body.innerHTML.toString().replace(/<div class="class-here-to-replace">/g, '<div class="my-class-here">');
};

benniaustin
12-20-2006, 10:17 PM
or you can just change the class using the id.

Place it right after the div you want to change, and it will change right when it's done loading.


<div class="someoldclass" id="myDiv">
Lorem ipsum dolor sit amet.
</div>

<script>
document.getElementById("myDiv").className = "mycoolnewclass";
</script>

or you could use it a a function in the header and then trigger it however you want.



<head>
<title>whatever...</title>
<script>
function changeClass(myElementID,newClassName) {
document.getElementById(myElementID).className = newClassName;
}
</script>
</head>
<body onload="changeClass('myDiv','mycoolnewclass')">
<div class="someoldclass" id="myDiv">
Lorem ipsum dolor sit amet.
</div>
</body>

Twey
12-21-2006, 05:05 PM
or you can just change the class using the id. That won't replace all instances, as was requested. Other than that, the principle is that of the first script I posted.

benniaustin
12-21-2006, 08:37 PM
Didn't see where he wanted every instance swapped. But yeah, Twey's solution should work fine for that.