简体   繁体   中英

How to select all elements with tag name 'div' but from another html?

I want to get all elements with tag 'div' but which are located on external page. I understand that for getting innerHTML of each DIV that is located on external page we have jquery load function which allows you to specify an element id to load. That's useful but I would like to know how to first find all that divs? If I had just one html file I would use
var divs= document.getElementsByTagName('div'); but I don't know what to do in this case

If you only have the URL of the other page, you can get the HTML of the page as a string using XMLHttpRequest . Save that string into a variable html . Then you can do:

var externalPage = document.createElement("div");
externalPage.innerHTML = html;
var divs = externalPage.getElementsByTagName("div");

Now divs is the NodeList of div elements of the other page.

If you already opened the other page using window.open() , you can instead use the return value of that call to access its document object:

var otherWindow = window.open("http://example.com/");
var divs = otherWindow.document.getElementsByTagName("div");

Note that in both cases you are subject to the same-origin policy.

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