1
Below I have a stylized list with the bootstrap
(defining the class of ul
and li
)
<!DOCTYPE html>
<html>
<head>
<link href="bootstrap-3.3.6-dist/css/bootstrap.min.css" rel="stylesheet">
<title>Add itens a lista</title>
</head>
<body>
<ul class="list-group">
<li class="list-group-item">item 1</li>
<li class="list-group-item">item 2</li>
<li class="list-group-item">item 3</li>
<li class="list-group-item">item 4</li>
<li class="list-group-item">item 5</li>
</ul>
</body>
</html>
However, I don’t need a static list, but rather a list that will be added by clicking on a button. So far I have the code below:
<!DOCTYPE html>
<html>
<head>
<link href="bootstrap-3.3.6-dist/css/bootstrap.min.css" rel="stylesheet">
<title>Add itens a lista</title>
<script>
function addItem() {
var li = document.createElement("li");
/* Aqui deveria ser atribuída a class list-group-li
* ao elemento li que acabou de ser criado
* para que o mesmo apresente o design da class
*/
li.class = "list-group-item";
/* Porém acredito que a sintaxe esteja errada */
li.innerHTML = "item n";
var ul = document.getElementById("lista");
ul.appendChild(li);
}
</script>
</head>
<body>
<ul class="list-group" id="lista">
<!--Aqui será inserido 1 item li ao clicar no botão input_add-->
</ul>
<form>
<input type=button id=input_add
value="Add item a lista" onclick="addItem()">
</form>
</body>
</html>
The feature of adding an item li
in the list works correctly, but I can’t define a class for it, class list-group-item
. The result then is as follows::
I need my read added by javascript code to have the same design as the first image. Any suggestions? This logic of assigning class to an already created element is correct?