Question

I have the following,

HTML,

<div id="testDiv" name="testHolder">
    Test Content
</div>

JS,

var testVar = document.getElementsByName('testHolder');
console.log(testVar);

I GET,

[object NodeList] 
[item: function]

OK, LET ME EXPLAIN AGAIN,

var testVar = document.getElementById('testDiv');
console.log(testVar);

RETURNS,

null

So, cannot read property [0] of null if adding index [0] to it ...why?

I want to get the string "Test Content" inside div.

UPDATE,

Seeing this object properties form the console.log when using getElementsByName,

innerHTML: "↵               Test Content↵             "
innerText: "Test Content"

Why am not able to isolate this?

Was it helpful?

Solution

document.getElementsByTagName returns an array of elements corresponding to a tag which is provided to the function as a parameter. The code outputs undefined to the console because testDiv is not an HTML tag. When using getElementsByTagName the script gets elements based upon the name (think type) of their tag, so names like div,span,ul,li,input,etc.

For example, document.getElementByTagName("div") will return all div elements on the page. It does not inspect the name attribute on a tag and return corresponding elements.

Here are a few examples to demonstrate the proper usage of these methods, they rely on your provided HTML:

//Retrieves Element By ID
var element = document.getElementById("testDiv");
alert("By Id: " + element.innerHTML);

//Retrieves By Tag
var element2 = document.getElementsByTagName("div");
//Remember this is an array we must specify an index
alert("By Tag Name: " + element2[0].innerHTML);

var doesntWork = document.getElementsByTagName("testHolder");
alert("By Tag Name: " + doesntWork[0].innerHTML);//Won't work

Demonstration: http://jsfiddle.net/TEJKB/

Make sure your executing this script after the DOM has loaded. For a simple test, place this script at the bottom of your page. If that works then you need to add an event handler to the window.onload event.

OTHER TIPS

You should use function getElementsByName to get the correct answer.

Both getElementsByName and getElementsByTagName returns a nodelist, so you further need to examine the result and get e.g. the first item:

var testVar = document.getElementsByName('testHolder');
if( testVar.length > 0 )
    alert( testVar[0].innerHTML );

getElement(s) always returning array object. you to add index number getElementsByTagName('testHolder')[0]. eg

var testVar = document.getElementsByTagName('testHolder')[0].innerHTML;
console.log(testVar);
var testVar = document.getElementById('testDiv');
console.log(testVar.innerHTML);

Or

var testVar = document.getElementById('testDiv').innerHTML;
console.log(testVar);

Should work...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top