Question

Here is my code :

var htmlVar= $("<div id=\"foo\"><div id=\"bar\">Content</div></div>");
var firstDiv= htmlVar.find("div").first();

This does not work as expected as the real first div "foo" is not taken into account. I wrapped my htmlVar into another div by doing this :

var htmlVar= $("<div>" + "<div id=\"foo\"><div id=\"bar\">Content</div></div>" + "</div>");

But this code is ugly and I am pretty sure there is some cleaner way to do this.

I would also like my code to always return the first div of an html var, whatever its structure. For example it should return the "foo" div for this case also :

var htmlVar= $("<html><body><div id=\"foo\">Content</div></body></html>");

Any ideas?

No correct solution

OTHER TIPS

var first = htmlVar[0];

or

var first = htmlVar.get(0);

If you have an HTML document like you have in your last example, you can easily run: $('div:first') to get the first div on the page.

The reason your first example didn't work is because the find command looks below its current element. Think of it like you are inside your house and you open the front door. You tell a computer to find the first house it sees. It will find your neighbors house since it is already inside your house and can't see itself. Hope that makes sense.

Have you tried splitting it up?

var htmlVar = $('<div />');
var newDiv = $('<div />').html('Content');
htmlVar.append(newDiv);

console.log(htmlVar.find('div:first'));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top