简体   繁体   中英

Fetch page with jQuery and extract all links with specific class

I want to fetch a page with jQuery and then extract values from the response, specifically I want to access all href attributes of a tags with a specific class .

The page is on the same domain, so there are no cross origin problems. The specific page returns a HTML page, but it would be great if it would work regardless of the content type.

What I have so far:

// the page to fetch (index2.html). 
<html>
<a href="/example" class="getthis">click</a>
<a href="/example2" class="getthis">click2</a>
</html>

On this page, this JS code works fine:

$('.getthis').each(function(){
    alert($(this).attr('href'));
})

What I now tried is this:

$.get('/index2.html', function(data){
    $(data).find('.getthis').each(function(){
        alert($(this).attr('href'));
    })
});

Fetching the page works fine, but extracting the data does not work. I tried a lot of variations on this idea, but none seem to work.

How can I fetch a HTML page with jQuery and then work on the DOM of the response, eg to extract all elements with a specific class?

I'm using jQuery 3.3.1, but it would be great if a solution would work on all versions.

Parse your data from ajax to DOM node via $.parseHTML() . And find element via .filter()

$.get('/index2.html', function(data){
    data = $.parseHTML(data);
    $(data).filter('.getthis').each(function(){
        alert($(this).attr('href'));
    })
});

I think,You can parse data like that

Create an invisible div

<div id="index2Data" style="display:none"></div>

and set data into this

$.get('/index2.html', function(data){
    var container = document.querySelector('#index2Data');
    var root = container.createShadowRoot();
    $(root).html(data);
    $(root).find('.getthis').each(function(){
        alert($(this).attr('href'));
    })
});

If you want to work directly with the "data" and typeof data === "string" as in your example this might work for you:

var links;

$.ajax('index2.html').done(function (data) {
    // note that data is just a string
    // get all a tags with specific class
    links = data.match(/<a.*class=['|"]getthis['|"].*>/gi);

    // iterate over links and ...
    links.forEach(function (item, index) {

        // remove everything in front of the href attr value ...
        var start = item.indexOf('href=') + 6;
        links[index] = item.substring(start);

        // then remove everything after the href attr value
        var end = links[index].indexOf('"') > - 1
        ? links[index].indexOf('"') 
        : links[index].indexOf('\'');

        links[index] = links[index].substring(0, end);
    });
});

console.log(links);

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