简体   繁体   English

jQuery添加具有特定id元素内的属性的新DOM元素

[英]jQuery adding new DOM elements having attributes within an element of specific id

Is there a methodToCreate in jQuery which could be written as 是否有一个jQuery中的methodToCreate可以写成

    $("#someId").methodToCreate("tagName", ".className");

where an element with tag tagName would be added and given a class className and that too inside a specific element which would have an id someId ? 在哪里添加一个带有tag tagName的元素,并给出一个类className ,并且在一个具有id someId的特定元素中也是someId

$("<tag></tag>").addClass("className").attr({id: 'someId'}).appendTo( "body" )

这是和单独设置所有属性的示例。

As pointed out such function doesn't exist, but you could always create one . 正如所指出的那样,这种功能不存在,但你可以随时创建一个。

(function( $ ){
$.fn.methodToCreate= function(tagName,className,id) {
  $(id).append("<"+tagName+" "+"class="+"\'"+className+"\'>"+"SampleContent"+"</"+tagName+">");
  return this;
}; 
})( jQuery );

and you can call this whenever you want in the following manner : 你可以按照以下方式随时调用它:

$(document).ready(function(){
$(document).methodToCreate('p','sampleClass','#someId');
});

Using this function( methodToCreate ) you can dynamically pass the tagName , className and id of the element that you want to append to. 使用此函数( methodToCreate ),您可以动态传递要追加的元素的tagNameclassNameid

Here is the working fiddle : https://jsfiddle.net/varunsinghal65/udrxeg9m/1/#&togetherjs=TBEnLAnNzJ 这是工作小提琴: https//jsfiddle.net/varunsinghal65/udrxeg9m/1/#&togetherjs=TBEnLAnNzJ

Using jQuery you can create an element 使用jQuery,您可以创建一个元素

var el = $('<tagName class="className"/>');

and then add it to a container 然后将其添加到容器中

$('#someId').append(el);
$('#someId').append('<tagname class="className"></tagname>');

如果您将类存储在变量中(例如myClass ),请不要忘记引用它:

$('#someId').append('<tagname class="' + myClass + '"></tagname>');

No that method does not exist, but you can use .appendTo 不存在该方法,但您可以使用.appendTo

like: 喜欢:

 $("<tagName class='className'></tagName>").appendTo("#someId");

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM