Find element in jQuery object built from HTML string

I would like to be able to build a jQuery object from an HTML string and search inside directly.

Example:

htmlString = '<h3>Foo</h3><div class="groups"></div>'
$html      = $(htmlString)
$groups    = $html.find('.groups') // Returns []. WTF?

I would expect to findreally find the element div.

If you want to know more about the context of my question, I am developing a Backbone application and to display certain views I have things like this:

render: ->
  $html   = $(@template(vehicle: @vehicle))
  $groups = $()

  _(@groups).each (group)=>
    subview = new App.Views.AttributesGroup(group: group, vehicle: @vehicle)
    $groups = $groups.add(subview.render().el)

  $(@el).html($html)
  $(@el).find('.groups').replaceWith($groups)
  @

I am looking for a more elegant way to achieve the same result.

Thank!


Thanks Matt, this is very clear. I feel stupid without thinking about this subtlety about descendants and brothers and sisters.

So, I reorganized my code:

render: ->
  $html   = $(@template(vehicle: @vehicle))
  $groups = $html.filter('.groups')

  _(@groups).each (group)=>
    subview = new App.Views.AttributesGroup(group: group, vehicle: @vehicle)
    $groups.append(subview.render().el)

  $(@el).html($html)
  @

Now there is only one DOM insert, and the code looks clearer to me.

+5
source share
1 answer

, find() jQuery, .groups jQuery, .

filter() .

htmlString = '<h3>Foo</h3><div class="groups"></div>'
$html      = $(htmlString)
$groups    = $html.filter('.groups');

, htmlString of <h3><span class="bar">Foo</span></h3><div class="groups"></div>, .bar; find().

, :

htmlString = '<h3>Foo</h3><div class="groups"></div>'
$html      = $(htmlString)
$groups    = $html.find('.groups').add($html.filter('.groups'));   
+7

All Articles