0

So I want to create a block of elements taking classes and attributes from an object.

I use a function to create the object

function profile(name, img, health, strength) {
    return {
        name: name,
        img: img
    }
};

Then I use jQuery to create a div and use the object to provide a class

function pushProfile(profile) {
    $('<div />', {
        "class": profile.name,
        "class": 'profile',
        text: 'test'
    }).appendTo('.profile-class');
};

So far it seems everything is working. My question is can I add nested elements to the new div inside the same function? Something like this?

function pushProfile(profile) {
    $('<div />', {
        "class": profile.name,
        "class": 'profile',
        text: 'test'
    }).appendTo('.profile-class');
    $('.' + profile.name).prepend('<img src=' + '"' + profile.img + '" />');
};

I'm fairly sure what I wrote for adding the img is wrong but I can't seem to find any documentation on someone doing anything similar to this so I may just be going about this wrong. If anyone has any suggestions on a different method I am absolutely open to those.

Thanks!

2
  • Do you have a fiddle or demo? Commented Jul 15, 2017 at 17:32
  • This should work. Once it's been added to the DOM you can just query it like you are doing now. Did you test it? Is it not working? Commented Jul 15, 2017 at 17:33

2 Answers 2

1

Set prepend as a property of attributes at jQuery(html, attributes)

function pushProfile(profile) {
    $('<div />', {
        "class": `${profile.name} profile`,
        text: 'test',
        prepend: `<img src="${profile.img}"/>`
    }).appendTo('.profile-class');
};

See also How to pass options objects as parameters to method set at second parameter of jQuery()?

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

Comments

0

Set all your properties within the Object of your your element constructor function

function pushProfile(profile) {
    $('<div />', {
        "class": profile.name + ' profile',
        text: 'test',
        prepend: '<img src="' + profile.img + '">',
        appendTo: '.profile-class'
    });
}

Comments

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.