3

I have a string containing html, including several divs. I need to get the html from one of those divs, which has the class '.image-desc'.

I thought I would be able to do the following, but it doesn't work:

$('<div class="image-title">Title</div><div class="image-desc">Description</div>').find('.image-desc').html();

Any ideas on how I can do this?

2 Answers 2

6

The problem is that .find() will search for children, not elements in the current jQuery object.

Use .filter() to filter the current selection:

$('<div class="image-title">Title</div><div class="image-desc">Description</div>')
    .filter('.image-desc').html();

Working example on jsfiddle

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Didier Ghys. I was almost there :)
1

What you're writing

$('<div class="image-title">Title</div><div class="image-desc">Description</div>')

will create a jQuery object containing two divs. So

$('<div class="image-title">Title</div><div class="image-desc">Description</div>').each(function(){
        if($(this).hasClass('image-desc')){
             //do whatever you want
        }
})

should work

EDIT : @Didier Ghys' answer is neater

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.