javascriptjqueryhtml

jQuery .load by element ID


Hi I'm trying to load an element from a webpage via ID.

My code reads the url from the 'href' attribute of the tag and then loads the page. I'm stripping the document anchor.

This script works but won't discard the surround elements and loads the entire page.

<script type="text/javascript">
$(function() {
    var a_href = $('#pycom').attr('href').split('#');
    $('div#pop-up').load(a_href[0] + '#synopsis');
});
</script>

<body>
    <a id="pycom" href="content/documentation/CommandsPython/ls.html#hFlags">ls</a>
</body>

The above link exists locally on my server (XAMPP) as per the 'html' code above.

Below is the element I would like to extract.

<p id="synopsis">
    <code>
        xform([objects...], 
        [<a href="#flagabsolute">absolute</a>=<i>boolean</i>], 
        [<a href="#flagboundingBox">boundingBox</a>=<i>boolean</i>],
        .....
        .....

    </code>

Thanks

Jamie


Solution

  • I was using jQuery 2.4.1 which apparently has a bug that is supposed to be fixed.. but appears to be not?? see here http://bugs.jquery.com/ticket/14773

    I am instead using jQuery 1.11.3

    below is my final code:

    <script type="text/javascript" src="content/scripts/jquery-1.11.3.js"></script>
    <script type="text/javascript">
        $(function() {
            var moveLeft = -10;
            var moveDown = 10;
    
            $('a#pycom').hover(function(e) {
                var a_href = $(this).attr('href').split('#');
                $('#pop-up').load(a_href[0] + ' #synopsis');
                $('div#pop-up').show().css('top', e.pageY + moveDown).css('left', ((e.width/100)*1) + moveLeft);
            }, function() {
                $('div#pop-up').hide();
            });
        });
    </script>
    

    The following method using .get also works exactly the same except gives the benefit of being able to process the returned string in the callback.. in this case the trailing section of the requested selected element... very nice stuff.

    $('a#pycom').hover(function(e) {
        var a_href = $(this).attr('href').split('#');
        $.get(a_href[0], function(response) {
            $('#pop-up').html($(response).filter('#synopsis').html().split('<br>')[0]);
            });    
        });
    

    jQuery .get in action!