Thursday, May 9, 2024
 Popular · Latest · Hot · Upcoming
96
rated 0 times [  99] [ 3]  / answers: 1 / hits: 17487  / 10 Years ago, sun, july 6, 2014, 12:00:00

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.


More From » dom

 Answers
17

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.


[#70301] Thursday, July 3, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
carolyn

Total Points: 618
Total Questions: 119
Total Answers: 86

Location: Saint Pierre and Miquelon
Member since Fri, Jan 28, 2022
2 Years ago
;