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>
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>
Share
Improve this question
edited Apr 15, 2014 at 21:17
Kara
6,22616 gold badges53 silver badges58 bronze badges
asked Aug 20, 2013 at 11:52
noobprogrammernoobprogrammer
1,1548 gold badges22 silver badges35 bronze badges
4
|
6 Answers
Reset to default 7document.getElementsByClassName("pagetitle")[0].innerHTML = "Goodbye";
Here is a working fiddle.
document.getElementById('title').getElementsByTagName('span')[0].innerHTML = 'Goodbye';
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
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";
Here is JSBin
Change by using getElementsByTagName('span')
document.getElementsByTagName('span')[0].innerHTML = 'Goodbye';
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);
.pagetitle
? – MDEV Commented Aug 20, 2013 at 11:58