4

How do I change/replace the text: "Hello" using javascript to say "Goodbye" instead?

<h1 class="titlearea win-type-ellipsis" id="title">
     <span class="pagetitle" >
            Hello
     </span>
</h1>
Kara
  • 6,115
  • 16
  • 50
  • 57
noobprogrammer
  • 1,140
  • 7
  • 22
  • 35
  • you are explicitly referring to javascript, but do consider using jQuery, it will make your javascript coding life a lot easier – Daniël Tulp Aug 20 '13 at 11:57
  • Is the inner span really required? Are there more elements with `.pagetitle` ? – MDEV Aug 20 '13 at 11:58
  • 1
    @DaniëlTulp Not to mention add pointless overhead for extremely simple tasks – MDEV Aug 20 '13 at 11:59
  • If this is the only javascript task, sure, but I assume with most modern websites/applications, it is not and as the jQuery library is so widely used and CDN's are available and the minified package is very small, I never think twice about using it – Daniël Tulp Aug 20 '13 at 12:03

6 Answers6

7
document.getElementsByClassName("pagetitle")[0].innerHTML = "Goodbye";

Here is a working fiddle.

Mithun Satheesh
  • 27,240
  • 14
  • 77
  • 101
  • We don't know that it's the first one on the page - which this code is currently assuming (granted it should be from the name.... but...) – MDEV Aug 20 '13 at 11:57
3
document.getElementById('title').getElementsByTagName('span')[0].innerHTML = 'Goodbye';
MDEV
  • 10,730
  • 2
  • 33
  • 49
1

If you're happy to give legacy browsers the finger (preferable):

document.querySelector('#title .pagetitle').innerHTML = 'Goodbye';

Support:

Chrome  Firefox (Gecko)  Internet Explorer  Opera  Safari (WebKit)
1       3.5 (1.9.1)      8                  10     3.2 (525.3)
        bug 416317                                 WebKit bug 16587

See also: document.querySelectorAll

Emissary
  • 9,954
  • 8
  • 54
  • 65
1
document.getElementsByClassName("pagetitle")[0].textContent = "Goodbye";

or

document.getElementsByClassName("pagetitle")[0].innerHTML = "Goodbye";

or

document.getElementById('title').getElementsByTagName('span')[0].textContent = 'Goodbye';

or

document.getElementById('title').getElementsByTagName('span')[0].innerHTML = 'Goodbye';

or

document.getElementById('title').getElementsByClassName("pagetitle")[0].textContent = "Goodbye";

or

document.getElementById('title').getElementsByClassName("pagetitle")[0].innerHTML = "Goodbye";
Runedrake
  • 21
  • 2
0

Here is JSBin

Change by using getElementsByTagName('span')

document.getElementsByTagName('span')[0].innerHTML = 'Goodbye';
Naveen Kumar Alone
  • 7,536
  • 5
  • 36
  • 57
0

Using innerHTML is not recommended according to XSS vulnerability, textContent is not supported by older version of browsers (ex. IE8). So will be better to create a TextNode

element = document.getElementByClassName("pagetitle");
txt = document.createTextNode("GoodBye");
element.appendChild(txt);