Get element by Id from another page

后端 未结 3 1534
慢半拍i
慢半拍i 2021-01-16 12:02

I need to change content of page1 if page2 contain specified element. This code works great if I get id from the same page

if (document.getElementById(\"page         


        
相关标签:
3条回答
  • 2021-01-16 12:34

    Think of it this way. JavaScript runs in the browser, say, Chrome. Chrome can see the page that is currently loaded, but has no knowledge of the html files that are still on the server, until they are brought into the browser. What you could do is have an iFrame containing logged.html that isn't visible (maybe 1x1 pixels, or a fixed position with a position off the page (left: 4000px). Then you can refer to the iFrame and get the element from there, this one explains how to reference an element in an iFrame: getElementById from iframe

    0 讨论(0)
  • 2021-01-16 12:45

    I think this might help you... Don't be too hard on me. This is my first post :p

    var element_change_content_page1 = "element_id_page1";
    var page2_datatype = "html";
    var filename_page2 = "logged.html";
    var target_element_id_page2 = "element_id_page2";
    var target_element_type_page2 = "div"
    
    $.get( filename_page2 , function(response, status){
    //You can also use jQuery " $.post() " Method instead of " $.get() "
    //Source: http://www.w3schools.com/jquery/ajax_get.asp
    var data = $('<div>' + response + '</div>');
    var target_element = data.find( target_element_type_page2 + '#'+ target_element_id_page2 )[0]; //There "might" be more div elements with the same id: specify index
    if(typeof target_element !== 'undefined'){
        //Page2 contains specified element
        var container = document.getElementById( element_change_content_page1 );
        container.innerHTML = "Content is changed!!!";
    } else {
        //Page2 DOES NOT contain specified element
    }
    }, page2_datatype);
    
    0 讨论(0)
  • 2021-01-16 12:51

    Think this will work...

    var iframe = document.getElementById("iframeId"),
        doc = getFrameDocument(iframe);
    
    doc.getElementById("page2_element_id"); // [DOM Element]
    
    function getFrameDocument(iframe){
        return iframe.contentDocument ? iframe.contentDocument : iframe.contentWindow.document;
    }
    

    return cond ? a : b means:

    if ( cond ) {
        return a;
    }
    else {
        return b;
    }
    
    0 讨论(0)
提交回复
热议问题