John
John

Reputation: 356

read a div from an html file to a javascript var

I want to read the colTwo div from the file members.html (in the same folder) into a variable, then set innerHTML to that variable. The result is 'undefined'. How can I fix this?

var fredpagevar;
 $.get("members.html", function(data){
     fredpagevar = $(data).find('#colTwo').html();
 });
function fredpage(){
    document.getElementById('boldStuff').innerHTML = fredpagevar;}

Upvotes: 0

Views: 125

Answers (3)

Adil Shaikh
Adil Shaikh

Reputation: 44740

based on your markup : <li><a href="#" onclick='fredpage()'>Fred</a></li>

Try this -

function fredpage(){
   $.get("members.html", function(data){
     $('#boldStuff').html($(data).find('#colTwo').html());
   }); 
}

Upvotes: 1

WooCaSh
WooCaSh

Reputation: 5212

This should work:

var fredpagevar;
$.get("members.html", function(data){
     fredpagevar = $(data).find('#colTwo').html();
}).done(function (){
    document.getElementById('boldStuff').innerHTML = fredpagevar;
});

Your function probably fired before get method receive data from file.


Or second usage (in case when you use your function in other place):

var fredpagevar;
$.get("members.html", function(data){
     fredpagevar = $(data).find('#colTwo').html();
}).done(fredpage());

function fredpage(){
    document.getElementById('boldStuff').innerHTML = fredpagevar;
}

Upvotes: 0

palaѕн
palaѕн

Reputation: 73906

You can simply do this:

$.get("members.html", function (data) {
    $('#boldStuff').html($(data).find('#colTwo').html());
});

Upvotes: 0

Related Questions