简体   繁体   中英

Getting error trying use textContent on an HTML error. “Unable to set property 'textContent' of undefined”

Think I'm missing something bleeding obvious here and would appreciate any help. Thanks in advance.

I have the following code however when I run it breaks and says that .textContent cannot be applied to queryString because queryString is undefined.

What is throwing me however is that if I break the code just before this line and look at queryString it is storing the correct value which is ".titlearea .pagetitle" . Why is this not translating in subsequent line?

The JSON object is converted into an object which returns two properties that I wish to use. A property called termName and another called definition . I want to replace the textContent of the two HTML elements with the values of these parameters.

I have stored the value of termName and definiton in an array called content . I do this in the for...in loop.

I then want to loop through this array and replace the relevant HTML element with the relevant value from the content array. This is the second for loop.

I basically want the line to be interpreted as:

document.querySelector(".titlearea .pagetitle").textContent = xxxx;

Where xxxx is the queryResult[i] value.

Here is the full code.

var searchTerm = JSON.parse(Result.responseText);
var DefDiv = ".titlearea .pagetitle";
var DescDiv = ".titlearea .pagesubtitle";
var holder = [DefDiv, DescDiv];
var content = [];
var x;

// Push the query into an array
for (x in searchTerm.terms[0].term) {
    content.push(x);
}

var displayResult = function(queryResult) {

    for (var i = 0; i <= holder.length; i++) {
        var queryString = holder[i];

        document.querySelector(queryString).textContent = queryResult[i];
    }
};

displayResult(content);

You tagged this as Windows 8, so I'm going to assume you're using some form of Internet Explorer. The thing is, some versions of IE don't support querySelector or querySelectorAll . I think this is your problem. Try logging these two methods and see what it says. If it returns undefined then there is no native support in that browser for those methods.


So it turns out it was because your were looping while using <= as part of the loop termination condition instead of < which I pointed out earlier but wasn't sure of that being the cause of the problem. Glad I could help anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM