0

I am building an jquery object:

 function build(){
     var first = $('<div/>', {
        class: 'first'
    });
    var second = $('<div/>', {
        class: 'second'
    });
    var third = $('<div/>', {
        class: 'third'
    });
    second.append(third);
    return first.append(second);
}

Now I want to append a new element to the third object after it was returned. Tried obj.find('.third').append(...) but this is not working. Any ideas how to do this?

Thanks.

8
  • You already have the reference to third, so you can just do third.append('your html here...'); Commented Jan 25, 2018 at 9:13
  • I don't get how obj.find is related, what did you try to do? Commented Jan 25, 2018 at 9:14
  • no. after return. So i get one object ´var obj = buildStuff()...´ reference is gone Commented Jan 25, 2018 at 9:15
  • Got a function which returns the object with the 3 divs. Now I want to append some ther objects to the inner div of the returned object. Commented Jan 25, 2018 at 9:16
  • In that case we need to see more of your code. What is obj? How are you appending first to the DOM? Commented Jan 25, 2018 at 9:16

1 Answer 1

1

Don't use find method. You can achieve the same with children()

Try this:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function getme(){
    var first = build();
    var fourth = $('<div/>', {
      class: 'fourth'
    });
    first.children().children().append(fourth)
    console.log(first);
}
function build(){
     var first = $('<div/>', {
        class: 'first'
    });
    var second = $('<div/>', {
        class: 'second'
    });
    var third = $('<div/>', {
        class: 'third'
    });
    second.append(third);
    return first.append(second);
}
</script>
</head>
<body>

<button onclick="getme()"/>

</body>
</html>
Sign up to request clarification or add additional context in comments.

2 Comments

Edited my code snippet. var obj = build(); Now i want to append to .third of obj.
Worked :) tried it before with children[0].children[0].append :) Thanks a lot :)

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.