jquery- get different page elements

前端 未结 4 670
别那么骄傲
别那么骄傲 2020-11-30 14:13

I want to get element attribute value which belongs to other html page.

For example if I am in file a.html and want to get data like element attribu

相关标签:
4条回答
  • 2020-11-30 14:49

    With jQuery you can load only parts of remote pages. Basic syntax:

    $('#result').load('ajax/test.html #container');
    

    The second part of the string is a basic jQuery selector. See the jQuery documentation.

    0 讨论(0)
  • 2020-11-30 14:55

    first you will have to fetch the b.html and then you can find the attribute value e.g.

    //if you dont want to display the data make the div hidden
          ^
    $("#someDivID").load("b.html",function(data){
    
    var value=$(data).find("#elementID").attr("attributeName");
    });
    
    0 讨论(0)
  • 2020-11-30 15:04

    By default, selectors perform their searches within the DOM starting at the document root.
    If you want to pass alternate context, you can pass to the optional second parameter to the $() function. For eg,

    $('#name', window.parent.frames[0].document).attr();

    0 讨论(0)
  • 2020-11-30 15:04

    Keep in mind that you can usually only make direct connections (like with $(..).load() to pages on the same domain you're currently on, or to domains that do not have CORS restrictions. (The vast majority of sites have CORS restrictions). If you want to load the content from a cross-domain page that has CORS restrictions, you'll have to make make the request through your server, and have your server make the request to the other site, then respond to your front-end script with the response.

    As for this question, if you want to achieve this result without jQuery, you can use DOMParser on the response text instead, to transform it into a document, and then you can use DOM methods on that document to retrieve the element, parse it as desired, and insert it (or data retrieved from it) onto the current page. For example:

    fetch('b.html') // replace with the URL of the external page
      .then(res => res.text())
      .then((responseText) => {
        const doc = new DOMParser().parseFromString(responseText, 'text/html');
        const targetElementOnOtherPage = doc.querySelector('img');
        const src = targetElementOnOtherPage.src;
        document.querySelector('#id').insertAdjacentHTML('beforeend', `<img src="${src}">`);
      })
      .catch((err) => {
        // There was an error, handle it here
      });
    
    0 讨论(0)
提交回复
热议问题