I would like to retrieve the following sites body content http://sports.espn.go.com/nhl/bottomline/scores?nhl_s_left1 and store it in a string, i know and am successful at retrieving this using php, however i want to restrict to using only javascript, is there a way just to take the string in the site and copy it and store it in a var?
Asked
Active
Viewed 1.3e+01k times
79
-
It's problematic to get content from remote page, but you can check this solution: http://stackoverflow.com/a/3076648/3208639. – damian004 Sep 26 '14 at 20:23
-
2Hey, Zak, I know it's been 8 years, buuuuut, maybe think about changing the accepted answer? I hate downvoting old answers because they're essentially wrong. =\ – HoldOffHunger Nov 24 '22 at 01:23
3 Answers
161
Although the @Brendan's answer is accepted and correct.
It is simple, short and faster enough to get a body element using
document.body;
It does the same as we can do with document.getElementsByTagName('body')[0];
, and it should be in the list of answers.

Lalit Mohan
- 2,685
- 2
- 16
- 16
-
And to use it even cleaner, just make it a variable `var body = document.body;` – Loosie94 Jul 06 '21 at 21:03
-
1
66
Try this:
<script>
window.onload = function get_body() {
body = document.getElementsByTagName('body')[0];
}
</script>
Allow me to explain. The window.onload
is so that the HTML loads before the script is executed. Even though there is only one body tag this is the method i use^. Basically, it finds the "first" body tag there is, then I tell it to just get the body element itself and not all the other attributes and child nodes that go along with it using an index of [0]
. If you want everything to do with the body tag then lose the index of 0. Hope this Helps!

Brendan
- 1,399
- 1
- 12
- 18
-
45
-
Yes but if he just wants the tag itself I have presented that option @FelixKling – Brendan Sep 26 '14 at 21:52
-
9Uh? `document.body` returns the same value as `document.getElementsByTagName('body')[0]` and is shorter to write. – Felix Kling Sep 26 '14 at 21:53
-