Jquery,在<div>标签内(括号内)添加文本,是否可能?</div>

时间:2013-07-26 08:28:58

标签: javascript jquery html dom

我想转此: <div class="foo" id="bar"></div>
进入:<div class="foo" id="bar" style="color:black" "whatever else comes in mind" ></div>

不仅仅是css或类等,但不管其他什么想法,jquery都可以从id或类中获取一个元素,并在其中添加内容。 &GT ;?
有可能吗?

3 个答案:

答案 0 :(得分:5)

我假设您要添加属性,因为添加的任何其他类型的文本都会使标记无效。所以你可以这样做:

一次显示多个属性

$(foo).attr({myNewAttribute1: "myNewAttributeValue1", myNewAttribute2: "myNewAttributeValue2"});

一次属性

$(foo).attr("myNewAttribute", "myNewAttributeValue");

答案 1 :(得分:0)

我想这可能是一种解决方法

var $bar = $('#bar')

$bar.replaceWith('<div class="'+$bar.attr('class')+'" id="'+$bar[0].id+'" style="color:black" "whatever else comes in mind" ></div>');

(我假设您不想添加新属性)

答案 2 :(得分:0)

找到<div class="foo" id="bar"></div>的父级,然后

$('#parent').html("<div class="foo" id="bar" style="color:black" "whatever else comes in mind" ></div>");