質問

This is driving me nuts. I'm inserting code into a page via Ajax. After the code is inserted I am running a function to grab the text of one of the DIVs and display it in another location on the page.

Can someone tell me why I keep getting a JavaScript error saying that currentText is null, even though the text displays properly in the other location in the page??

var currentText = document.getElementById("current-text"),
updatedTextHere = document.getElementById("updated-text-here");

updatedTextHere.innerHTML = currentText.firstChild.nodeValue;

This is the code it's grabbing the text value from, which is inserted into the main page via Ajax:

<div id="current-text" class="hide">January 1, 2011</div>

UPDATE:

Here's how it looks:

getDate = function () {
    var currentText = document.getElementById("current-text"),
    updatedTextHere = document.getElementById("updated-text-here");

    updatedTextHere.innerHTML = currentText.firstChild.nodeValue;
},

htmlready = function () {
    myDiv.innerHTML = xmlRequest.responseText;
    getDate();
},
役に立ちましたか?

解決

The issue you are having is that firstChild isn't a node of currentText. Your nodeValue doesn't have a value because it doesn't exist. You should use innerHTML or textContent instead.

Change to...

updatedTextHere.innerHTML = currentText.firstChild.textContent; // or innerHTML
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top