I see a lot of people in here giving answers that requires you to create a new element in the html page through Javascript using "document.createElement" and other methods. I can understand this to a certain extent, but is it really always necessary?
For example, when I build my own nonprofessional pages, they always require user input. As their input is being done, there are locations in the html file that displays the results based on whatever was typed by the user. I make all the tags beforehand in the html file, so all I need to do is simply apply the javascript results to the specific id in the html. However, as mentioned already, apparently a lot of people like to create the elements within the Javascript itself and send it to the html through document.createElement or using variables like var group = $('<div class="group"></div>');
and etc. Am I doing a bad habit and this is really the best way to do it?
Let's suppose I need to make a list that displays info based on what the user typed in. What I do is have the list ready and done in the html with no display, ready to be shown only after the time is ready, instead of coding stuff like:
var list = $('<ul class="legend"></ul>');
var listItem = $('<li><span class="example' + i + '"></span>' + this
+ '</li>').appendTo(list); //in a loop, etc.
I can understand sometimes having to create stuff out of the js, but personally I prefer having everything set and done at html just waiting to be used, and I wonder if this is a bad thing. Thanks in advance for the answers.
Edit: Thanks a lot for the answers, I really appreciate. I'd like to put another example here, although I think the idea itself is already clear as is. I understand the need of having to update the page's content dynamically depending on the situation, but what I really had in mind was: On a situation where the table/list/whatever is going to be displayed in a preestablished way where nothing will be added or subtracted, is there any need to use the above method? For example, I find it a lot easier to type this in the html:
<input type='button' onclick='display(2)' value='Click me'>
than this in js:
var inputElement = document.createElement('input');
inputElement.type = 'button';
inputElement.value = 'Click me';
inputElement.addEventListener('click', function(){
display(2);
});
document.body.appendChild(inputElement);
Both of these do pretty much the same thing, with the exception the first is already inserted in the html, while the second is created through js. The main question that is being asked here is: In a situation where everything is already predetermined and there's nothing the user can do to change how the page will be displayed, is there any reason of why I should do the js method in the example above, instead of the html one?
<li>
for every item in the list. You can't exactly create all possible<li>
s from the beginning, right? Sometimes you have to generate new elements.