문제

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?

도움이 되었습니까?

해결책

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

다른 팁

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>');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top