Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

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>');
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top