Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get body element of site using only javascript

Tags:

javascript

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?

like image 588
Zak Avatar asked Sep 26 '14 20:09

Zak


People also ask

How do you target a body in Javascript?

body. className = ''; This will change the contents of the class attribute to be the empty string, so it will remove all the classes the element might have.

How do you get all the elements in a page using JS?

Use the querySelectorAll() method to get all elements by type, e.g. document. querySelectorAll('input[type="text"]') . The method returns a NodeList containing the elements that match the provided selector.

Is document body an element?

document. body is the element that contains the content for the document.

How do I get all the elements in a page?

You used getElementById() to retrieve an element with a specific ID, getElementsByTagName() to get all the elements of a certain type, and getElementsByName() to find all elements with a particular name attribute.


2 Answers

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.

like image 96
Lalit Mohan Avatar answered Sep 21 '22 21:09

Lalit Mohan


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!

like image 27
Brendan Avatar answered Sep 21 '22 21:09

Brendan