Question

Let's say I have a following code:

function createElement(element) {
  $('#container').append(element);
}
createElement('<div id='abc'>Some content</div>');

I'd like to let the function know which element id it creating (hopefully without parsing of the element string) to manipulate with just created element such as setting the position.

Is there any solution?

Was it helpful?

Solution

function createElement(element) {
   var node = $(element);
   $('#container').append(node);
   alert(node.attr('id'));
}
createElement('<div id="abc">Some content</div>');

See the working code at:

JSFiddle

OTHER TIPS

Try using .appendTo() in this context,

function createElement(element) {
   return $(element).appendTo('#container');
}

console.log(createElement('<div id="abc">Some content</div>').attr('id'))

just do:

function createElement(element) {
  $('#container').append(element);
    return $(element).attr("id");
}
console.log(createElement('<div id="abc">Some content</div>'));

Demo:: jsFiddle

You can use this.id to get the id like this:

function createElement(element) {
  var id = $(element).attr('id');//and do your stuff with the id
  $('#container').append(element);
}
createElement('<div id="abc">Some content</div>');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top