Nate Glenn
Nate Glenn

Reputation: 6744

Creating nested elements in JQuery using $() constructor

I can't get JQuery's $() element constructor to work right. The following works right (using expect.js for the expect() calls):

var p = $('<div id="1"><div id="2">middle div</div></div>');
expect(p.children('div')).not.to.be(undefined); //passes
expect(p.children('div').attr('id')).to.equal('2'); //passes

But the following doesn't work

var p = $('<p id="1"><div id="2">middle div</div></p>');
expect(p.children('div')).not.to.be(undefined); //passes
expect(p.children('div').attr('id')).to.equal('2'); //fails

Any tips on how to get this to work right?

Upvotes: 1

Views: 125

Answers (3)

ryandawkins
ryandawkins

Reputation: 1545

You should try this:

expect($('#1').find('div').attr('id').to.equal('2');

Edit: Niko and The System are right.. a div cannot be in a p though.

Upvotes: 1

Niko
Niko

Reputation: 26730

The HTML markup is wrong. You cannot put a block-level element like <div> into a <p> element. That's why the HTML is actually (I think this depends on the browser) most likely parsed as:

<p id="1"></p><div id="2">middle div</div>

or (in chrome):

<p id="1"></p><div id="2">middle div</div><p></p>

You can verify this easily via console.log(p);

Upvotes: 3

the system
the system

Reputation: 9336

The <div> is being ejected because it's not valid to have a <div> inside a <p>.

Upvotes: 1

Related Questions