I am using javascript from few days. And i am confusing between getElementById and createElement.
THANKS IN ADVANCE
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The main difference is that
getElementByIdwill get an element from the DOM by it’s ID attribute, andcreateElementwill create an entirely new DOM element.Let’s say you had a page with the following HTML:
And then you had some JavaScript code like so:
You will retrieve the
<div>element that has anidattribute of"message".Now, let’s say you wanted to add a new element to your HTML page, then you’d use the
createElementfunction.Of course, from the example, we are also storing the new element in a variable called
newEl.Now, to actually append the new element, we’d have to call
appendChildon any DOM element. For the sake of simplicity, we’re going to simply append to the<body>tag.Now, your page should (at least in the mind of the browser) look like so: