![](/img/trans.png)
[英]How to check if parent element in html is specific tagname (e.g. span) using Javascript
[英]How to createText and append text to an existing element e.g. empty span?
在我搜索过的所有地方,我只能找到创建新元素后追加textnode的方法。 例如,他们将创建一个新的段落( p
)元素,然后将textnode追加到该新段落。 但我想将textnode添加到现有元素(在我的情况下为空跨度)。
链接到示例代码和说明http://pastebin.com/K1EBMr4Z
<span class="span"></span> <!-- append textnode here -->
function newFunction(){
var textnode = document.createTextNode("OK");
// Append my `textnode` to the empty span here
}
提前致谢
这很简单。 使用appendChild方法。
function newFunction(){
var textnode = document.createTextNode("OK");
document.querySelector(".span").appendChild(textnode);
}
如注释中所述,您可以使用appendChild()
方法将文本节点添加为跨度的子级。
对于文本,您也可以只设置span的innerHTML
属性。
这两个示例都位于垃圾箱中:
function newFunction(){
var span = document.getElementById('my-span');
var otherSpan = document.getElementById('my-other-span');
span.innerHTML = 'Yo this is text';
var textNode = document.createTextNode("OK");
otherSpan.appendChild(textNode);
};
newFunction();
如果为跨度指定一个ID,则可以使用document.getElementById()获取它,然后在该元素中更改html。 这是执行此操作的SO的链接。 另外,这是innerHTML和getElementByID的一些文档。
您需要首先选择要附加textNode的节点。 然后,将textNode附加到该选定节点(在您的情况下为.span
元素)。
<span class="span"></span>
function newFunction(){
var textnode = document.createTextNode("Hello World!");
// Select your existing element
var empty_span = document.querySelector('.span');
// Append the element
empty_span.appendChild(textnode);
}
newFunction();
示例jsFiddle也是如此。
为什么不使用jQuery:
$('span').text('text');
要么
$('span').html('<p>text</p>');
如果不使用它,请使用:
document.getElementsByTagName('span').innerHTM = '<p>text</p>';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.