Selecting the first H1
Published: Tuesday, Nov 4, 2008 Last modified: Monday, Dec 9, 2024
DOM manipulation in Javascript sucks:
var h1 = document.getElementsByTagName("h1");
h1.item(0).childNodes.item(0).nodeValue = "Hello World";
or (thank to Xiven):
document.getElementsByTagName("h1")[0].childNodes[0].nodeValue
Using CSS selector style (better imo):
$('h1:first').text("Hello World");
or
$('h1:eq(0)').text("Hello World");
One wonders why it isn’t as easy as getElementsByTagName("h1")[0].text("Hello World")
?