.getElementsByTagName()
returns a node list. The following:
document.getElementsByTagName('p').innerText
attempts to get the .innerText
of that node list, but node lists don't have .innerText
, only individual nodes do. You must access one of the nodes in the list and then you can get its .innerText
, like this:
document.getElementsByTagName('p')[0].innerText
Also, at the time that you have the console open and are typing into it, the document has been fully parsed. Your same test, but with code in the file is being attempted prior to the p
elements being parsed.
Make sure you have your script
tag located just before the closing body
tag in your document so that by the time it is encountered, all HTML will have been parsed into memory.
Examples:
<!doctype html>
<html>
<head>
<title>Attempting to get DOM references too early</title>
<script>
// This will fail because, at this point, the <p> hasn't been parsed yet
console.log(document.querySelector("p").textContent);
</script>
</head>
<body>
<p>Test</p>
</body>
</html>
<!doctype html>
<html>
<head>
<title>Getting DOM references after the DOM is ready</title>
</head>
<body>
<p>Test</p>
<script>
// This will work because, at this point, the <p> has been parsed
console.log(document.querySelector("p").textContent);
</script>
</body>
</html>
FYI:
.getElementsByTagName()
returns a "live" node list that can hinder page performance because every time the variable is
accessed, the entire document must be searched again to ensure you
have the most up-to-date collection. This is not appropriate in many
use-cases (especially if your document isn't dynamically
adding/removing elements). So, in most cases, use
.querySelectorAll()
instead, as this method returns a "static" node list.
.innerText
is a "de facto" standard, but it works differently than
.textContent
, which is an actual standard. Use .textContent
instead.