How to change a text from a header element in Javascript?

Asked

Viewed 3,050 times

1

What is the best function that changes the text of a header element (h1, h2, h3, etc) through Javascript?

I tried this way to change the text:

function mudarTexto(id, novoTexto){
  document.getElementById(id).innerText = novoTexto;
}

But the text remains the same. See the example I created on Jsfiddle

1 answer

3


Your code is correct and it works. The problem is that jsFiddle encapsulates your Javascript within an onload function and then your function is out of scope for what’s in html.

Switch to jsFiddle noWrap and it already works.

inserir a descrição da imagem aqui

Working version: http://jsfiddle.net/2304rpnf/2/

If you want to use this on a website then you can put the function in the document, wherever you want. Since it is defining a function only, then it does not need to be within any other function onload or domready.

Example: http://jsfiddle.net/2304rpnf/3/

If you want to insert this code into a separate file you can add to the page with

<script src="oMeuScript.js"></script> 

in the event of being on the same board as the index.html. If you are not have to show the path from root: src="/ < caminho > /oMeuScript.js"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.