Simon Appelt
Simon Appelt

Reputation: 305

jQuery Selector inside of variable?

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!

Upvotes: 10

Views: 5195

Answers (4)

epascarello
epascarello

Reputation: 207511

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);

Upvotes: 4

Rob Johnstone
Rob Johnstone

Reputation: 1734

try:

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

Upvotes: 0

Ram
Ram

Reputation: 144689

$.get("blocks.html", function(data) {
    var ids = $('<div/>').html(data).find('div.block').map(function() {
        return this.id;
    }).get();
});

Upvotes: 10

A. Wolff
A. Wolff

Reputation: 74420

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

Upvotes: 8

Related Questions