2

i have a div:

<div id="div"></div>

with

$("#div").append("<div id='c'></div>")
$("#c").length 

returns 0. what i can do for find the div width id = c after inserted in div #div?

thanks

5 Answers 5

2

It does work for me: http://jsfiddle.net/4Q4cM/

Maybe #div element isn't appended to DOM tree itself? E.g., you're doing $('<div id="div"></div>') instead of inserting it in the document. Nick Craver also has a good guess.

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

Comments

1

try doing:

$('div').append($('<div>').attr('id', 'c'))

Comments

1

What you have will work as long as you're running it in a document.ready handler, like this:

$(function() {
  $("#div").append("<div id='c'></div>")
  alert($("#c").length );  //alerts 1
});

You can test it here, without the .ready wrapper, if it runs before <div id="div"></div> is loaded in the DOM, that #div selector won't find anything, and so it won't append anything to the 0 elements it found.

Comments

-1

First off, he div won't have a width until it contains some content. Try that.

2 Comments

I think you're misunderstanding the length() property (in this case the 'length' is basically the number of elements found by the selector), whereas you seem to be confusing it with width.
whoops. I did indeed miss that, sorry.
-2
$("#div #c")

will find what you're looking for

1 Comment

You should very rarely use a selector like this, an ID selector should only be #id in almost every case. In this case it's not the issue.

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.