sellmeadog
sellmeadog

Reputation: 7517

jQuery - from an HTML string, find all elements with a given data attribute

Using jQuery, I am trying to find all elements with a data-inject attribute from an HTML string returned from the server. Here's an example HTML string:

var html = '<div class="container-fluid">
              <div class="row-fluid">
                <div data-inject="ViewModel1" class="span12"></div>
              </div>
            </div>
            <div data-inject="ViewModel2" class="navbar navbar-fixed-bottom"></div>';

I can't seem to find a way to get both divs and the problem seems to be the fact that I'm starting with a HTML string.

Here's a fiddle showing that just querying the DOM with $('[data-inject]') returns the two elements as expected. However, querying the HTML string with $('[data-inject]', html) only returns one element (the ViewModel1 element).

Anyone know what I'm doing wrong and how to get the expected result?

Upvotes: 2

Views: 1240

Answers (1)

PSL
PSL

Reputation: 123739

That is because you don't have a root element. Just temporarily use wrapAll during the query.

var html = '<div class="container-fluid"><div class="row-fluid"><div data-inject="TowerLogsViewModel" class="span12"></div></div></div><div data-inject="TowerLogFormViewModel" class="navbar navbar-fixed-bottom"></div>';
var $html = $(html);

$('[data-inject]', $html.wrapAll($('<div>')).parent()).each(function (ix, el) {
    console.log($(el).data('inject'));
});

Demo

Due to the absence of root element the collection this will find data-inject from the first element in the collection i.e <div class="container-fluid"> so you get only one. if you use filter you will get only the other one. Hence wrap them temporarily.

Upvotes: 6

Related Questions