i'm currently learning javascript and had a question. I am trying to target only the h1 tag in the div id=title i tried a few ways using this as a reference site amongst others: http://www.ibm.com/developerworks/library/wa-jsanddom-pr/sidefile1.html
but nothing seems to be working, i get back the value "undefined" esentially what i want to do is only target the h1 and change the text to something else. how do i do that? is this along the right path or is there a different way to do it?
<div id="title">
<h1>Javascript Lesson 1</h1>
<p>The basics</p>
</div>
<script>
var title = document.getElementById('title');
var titleHeading = title.firstChild;
console.log (title.value);
</script>
any help is greatly appreciated. Thanks.
Take a look at Element.getElementsByTagName.
var titleElement = document.getElementById("title");
var titleChildren = titleElement.getElementsByTagName("H1");
// Do something with children.
// In your example code, you'll only have one element returned
console.log(titleChildren[0].innerHTML);
// To change the text, simply access the innerHTML property
titleChildren[0].innerHTML = "[New Value]"
Here's a working fiddle to play with.
If you know that the h1 you want to modify will always be the first h1 child you could do something like this:
<script>
document.getElementById('title').getElementsByTagName("h1")[0].innerHTML = "New Name";
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With