2

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?

1 Answer 1

6

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.

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

1 Comment

Can you please confirm/describe what line 2 does? Does jQuery convert the string into actual objects, still not bound to the DOM?

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.