SQLesion
SQLesion

Reputation: 165

extract the text of a DOM element into a string var - why undefined?

I am new to JS development, and using jsonlib.fetch to get a JSON object and sidestep cross-domain issues in the browser. I wrote the response to a DOM element that i hide with CSS, and want to set a variable to the string I get back (JSON object) and convert it to an array for use later in the program.

jsonlib.fetch(apiurl, function(m) {

  $(".allQuestion").text(m.content);

 });

var allQuestions = $(".allQuestion").text();

However, I get undefined or a number of blank characters when I write allQuestions to the console. Why? Is there a better way to do this in general?

Upvotes: 0

Views: 37

Answers (1)

tymeJV
tymeJV

Reputation: 104785

It's because the fetch method is an async method, so that method is still in progress when you try to grab the text. Do all your logic within the callback:

jsonlib.fetch(apiurl, function(m) {
    $(".allQuestion").text(m.content);
    var allQuestions = $(".allQuestion").text();
});

Upvotes: 1

Related Questions