jQuery Selector inside of variable?

2020-07-06 07:26发布

Hi I'm trying to get the IDs of all DIVs, inside another HTML File, with a specific Class. To load the file I use:

$.get("blocks.html", function(data) {
        //here I don't know how :)
});

Now what I'm looking for ist something like this:

data.$('.block').each(... the rest is no problem

so that I use the jQuery selectors not on my page code but instead inside the contend of the data variable. Thanks for help!

4条回答
太酷不给撩
2楼-- · 2020-07-06 07:59

try:

$.get("blocks.html", function(data) {
        $(data).find('.block').each(...
});
查看更多
看我几分像从前
3楼-- · 2020-07-06 08:00

Try this:

$.get("blocks.html", function(data) {
        $(data).find('.block').each(function(){...});
});

If your 'data html' containing element is a '.block', look at @undefined's answer

查看更多
Explosion°爆炸
4楼-- · 2020-07-06 08:13

The answer really depends on what the responseText looks like that is being returned from the GET request. Based on that you would have to wrap it or not.

With Parent

If the response is nested inside of a parent tag.

Response Mark Up:

<div>
   <div id="someId1"></div>
   <div id="yourId" class="block"></div>
   <div id="someId2"></div>
</div>

JavaScript:

var htmlFiltered = $(html).find('.block');

Without Parent

If the response does not have a parent node wrapping the content, you would need to add the parent node or use filter.

Response Mark Up:

<div id="someId1"></div>
<div id="yourId" class="block"></div>
<div id="someId2"></div>

JavaScript:

var htmlFiltered = $(data).filter('.block');

or

var htmlFiltered = $("<div/>").html(data).find('.block');

Getting the ids

You can than use map() or each() on htmlFiltered to get the ids.

With each()

var ids = [];
htmlFiltered.each( function () {
 ids.push(this.id);   
});
console.log(ids);

With map()

var ids = $.map(htmlFiltered, function (elem) {
 return elem.id;   
});
console.log(ids);
查看更多
疯言疯语
5楼-- · 2020-07-06 08:17
$.get("blocks.html", function(data) {
    var ids = $('<div/>').html(data).find('div.block').map(function() {
        return this.id;
    }).get();
});
查看更多
登录 后发表回答