Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Targeting Child Elements in a ID

Tags:

javascript

dom

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.

like image 430
Nicholas Ritson Avatar asked Jul 06 '14 13:07

Nicholas Ritson


2 Answers

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.

like image 80
James Hill Avatar answered Oct 04 '22 12:10

James Hill


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>
like image 42
BeaumontTaz Avatar answered Oct 04 '22 13:10

BeaumontTaz