user3367171
user3367171

Reputation: 23

How to retrieve the first div of an HTML variable

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?

Upvotes: 0

Views: 92

Answers (3)

jpaddock
jpaddock

Reputation: 21

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.

Upvotes: 1

Cjmarkham
Cjmarkham

Reputation: 9681

Have you tried splitting it up?

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

console.log(htmlVar.find('div:first'));

Upvotes: 0

QBM5
QBM5

Reputation: 2788

var first = htmlVar[0];

or

var first = htmlVar.get(0);

Upvotes: 1

Related Questions