Hi,
If I wish to add a <p> tag, is it necessary to first get the body tag and then add append p to it? Or is the body tag already got?
I see that when using the getElementsByTagName you need to use body like this,
var blah = document.body.getElementsByTagName("h1");
But when doing it by id you don’t need body, like this,
var blah = document.getElementById("one");
So if I simply want to append a p to the body do I need to call the body. This doesn’t seem to make sense as I have to use body anyway. So I am sure this must be wrong,
var bod = document.body.getElementsByTagName("body"); // get the body tag
var para = document.createElement(p); //create a paragraph tag
var tex = document.createTextNode("This is a test"); //create a text node with text inside it
para.appendChild(tex); //append the text node to the paragraph
bod.appendChild(para); //append the paragraph to the body
Any thoughts on this would be appreciated,
Thanks,
Shane
var bod = document.body.getElementsByTagName("body"); // get the body tag
var para = document.createElement(p); //create a paragraph tag
var tex = document.createTextNode("This is a test"); //create a text node with text inside it
para.appendChild(tex); //append the text node to the paragraph
bod.appendChild(para); //append the paragraph to the body
This could be written as this:
var p = document.createElement(p);
p.innerHTML = "This is a test"
document.body.appendChild(p);
Regarding your final example, you could alter the code to make it a little more rreadable, thus:
function isValidKey(v){
return v === 82 || v === 71 || v === 66;
}
function changeBackgroundColor(k){
opts = {
82: "red",
71: "green",
66: "blue"
}
document.body.style.background = opts[k];
}
document.addEventListener("keydown", function(e){
if (isValidKey(e.keyCode)){
changeBackgroundColor(e.which);
}
});
Hi,
Sorry for taking so long to reply. Thanks for clarifying this.
Your code is a fantastic way of doping it, I certainly wouldn’t have thought of this.
Thanks again,
Shane