RSS

As vezes temos a necessidade de criar alguns elementos em HTML, só que há ocasiões que não nos possibilita mexer na estrutura HTML existente. Ainda bem que isso não é problema para o javascript. Vou mostrar uma formas bem simples de criar esses elementos com o innerHTML.

Alterar o texto de um elemento HTML – innerHTML

A maneira mais fácil de obter ou modificar o conteúdo de um elemento é usar a propriedade innerHTML:

Exemplo:
Vamos alterar o texto de um elemento:
<html>
<body>
<p id="p1">Hello World!</p>
<script type="text/javascript">
document.getElementById("p1").innerHTML="New text!";
</script>
</body>
</html>

Alterar o texto de um elemento – com uma função

O seguinte exemplo usa uma função para alterar o texto do elemento quando um botão é clicado:
<html>
<head>
<script type="text/javascript">
function ChangeText()
{
document.getElementById("p1").innerHTML="New text!";
}
</script>
</head>
<body>
<p id="p1">Hello world!</p>
<input type="button" onclick="ChangeText()" value="Change text" />
</body>
</html>

Alterar o tipo de letra e cor de um elemento


<html>
<head>
<script type="text/javascript">
function ChangeStyle()
{
document.getElementById("p1").style.color="blue";
document.getElementById("p1").style.fontFamily="Arial";
}
</script>
</head>
<body>
<p id="p1">Hello world!</p>
<input type="button" onclick="ChangeStyle()" value="Change style" />
</body>
</html>

É isso aí, bem simples. Até a próxima.

Popularity: 13% [?]

Leave a Reply