Theoretically, this code should write Paragraph 1-4 into links to www.bing.ca with Paragraph (Number) as the text. I have been working on finding the error for a couple days now and I am failing miserably. Any help would be appreciated. This is my first question ever, so if I could have made it any better for future reference to others, I'd appreciate that as well. Thank you.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
<script>
window.onload = function() {
var innerDiv = document.getElementById("innerDiv");
var newDiv = document.createElement("div");
for (var i = 0; i < innerDiv.childNodes.length; i++) {
var anchor =
newDiv.appendChild(document.createElement("a"));
anchor.setAttribute("href", "http://www.bing.ca");
anchor.text = innerDiv.childNodes[i].textContent;
newDiv.appendChild(document.createElement("br"));
}
innerDiv.replaceNode(newDiv);
}
</script>
</head>
<body>
<div id="outerDiv">
<p class='mainPara'>Main Paragraph</p>
<ul>
<li>First List Item</li>
<li>Second List Item</li>
<li>Third List Item</li>
<li>Fourth List Item</li>
</ul>
<div id="innerDiv">
<p class='subPara' id='P1'>Paragraph 1</p>
<p class='subPara' id='P2'>Paragraph 2</p>
<p class='subPara' id='P3'>Paragraph 3</p>
<p class='subPara' id='P4'>Paragraph 4</p>
</div>
<table>
</table>
<input type="text"/><input type="submit" value="Submit!">
</body>
</html>
Note that replaceNode
is IE only (http://help.dottoro.com/ljxvjvcg.php). Perhaps use innerHTML
instead.
var innerDiv = document.getElementById("innerDiv");
var newDiv = document.createElement("div");
for (var i = 0; i < innerDiv.childNodes.length; i++) {
var anchor =
newDiv.appendChild(document.createElement("a"));
anchor.setAttribute("href", "http://www.bing.ca");
anchor.text = innerDiv.childNodes[i].textContent;
newDiv.appendChild(document.createElement("br"));
}
innerDiv.innerHTML = newDiv.innerHTML;
<div id="outerDiv">
<p class='mainPara'>Main Paragraph</p>
<ul>
<li>First List Item</li>
<li>Second List Item</li>
<li>Third List Item</li>
<li>Fourth List Item</li>
</ul>
<div id="innerDiv">
<p class='subPara' id='P1'>Paragraph 1</p>
<p class='subPara' id='P2'>Paragraph 2</p>
<p class='subPara' id='P3'>Paragraph 3</p>
<p class='subPara' id='P4'>Paragraph 4</p>
</div>
<table>
</table>
<input type="text" />
<input type="submit" value="Submit!">
Always check your console for errors, or turn javascript errors on in your browser for debugging. A quick check of your console would have shown
TypeError: innerDiv.replaceNode is not a function
and you would have been well on the way to solving your problem yourself.