I’m really a beginner in Javascript and trying to add a p element inside a div element in this HTML :
<!doctype html>
<html>
<head>
</head>
<body>
<p>This is paragraph 1.</p>
<p>This is paragraph 2.</p>
<p>This is paragraph 3.</p>
<p>This is paragraph 4.</p>
<div>
<p id="foo">This is paragraph 5.</p>
</div>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
using this code :
(function(){
var divElement = document.getElementsByTagName("div");
el = document.createElement("p");
content = document.createTextNode("This is text");
el.appendChild(content);
document.divElement.appendChild(el);
}());
But i get this error at line 6 :
Uncaught TypeError: Cannot call method ‘appendChild’ of undefined
getElementsByTagName(" ... ")returns a collection of elements.Also, change:
To: