I thought this would be easier to find :)
$.get('/page.html', function(data) {
//get only contents of class="contents"
});
I can't seem to find out how to do that.
I thought this would be easier to find :)
$.get('/page.html', function(data) {
//get only contents of class="contents"
});
I can't seem to find out how to do that.
Just use .find()
:
$(data).find(".contents")
Here's the final code you could use:
$.get('/page.html', function(data) {
var contents = $(data).find(".contents");
});
Then depending on what type of element the .contents
is, you could use contents.html()
or contents.text()
(most elements), or contents.val()
(input element).
Technically, another idea is to use .filter()
.
This all depends on the structure of your HTML in data
. If your structure is like this:
<div id="main">
blah blah
<div class="contents"></div>
</div>
Then the result of $(data)
will be [#main]
and you need to use find
. If your structure is like:
<div id="main"><div>
<div class="contents"></div>
<div class="another"></div>
Then the result of $(data)
will be [#main, .contents, .another]
and you need to use filter
.
Of course, combining them, it could be:
$.get('/page.html', function(data) {
var all = $(data), contents;
contents = all.filter(".contents");
if (!contents.length) {
contents = all.find(".contents");
}
if (contents.length) {
// It/they was/were found at some point
}
});
I would do something like this...
$.get('/page.html', function(data){
var $page = $(data)
var $contents = $page.filter('.contents'); /* this will get a reference to the .contents */
/* do more stuff here
....
*/
});
Have a look at the accepted answer to this SO: Get HTML of div element returned by .get with jQuery
If the structure of the returned content is uncertain (to where sometimes you would need to use .find()
due to .contents
being a descendent, you could always perform a check and run .filter()
or vice versa.
Example:
$contents = $page.filter('.contents');
if($contents.length == 0) {
$contents = $page.find('.contents');
}
Just a thought based on the comments posted in other answers.
If you create a jQuery object from the returned data
and the wrapper element in the jQuery set is .contents
element then find
fails to find the target element and if the contents
element is a descendant element then filter
method fails to select that element. You can create a dummy element, populate it with returned data and use find
method.
$.get('/page.html', function(data) {
var element = $('<div/>').html(data).find('.contents');
});