使用Javascript在内容之前添加元素 [英] Append element in tag right before contents with Javascript
本文介绍了使用Javascript在内容之前添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我将举例说明:我需要使用javascript转换以下html
I'll illustrate with an example: I need to convert the following html with javascript
<a>Text 1</a>
<a>Text 2</a>
<a>Text 3</a>
...
代码
<a><input/>Text 1</a>
<a><input/>Text 2</a>
<a><input/>Text 3</a>
...
我不知道如何使用createElement实现这一目标, appendChild或insertBefore / After。
I don't have a clue how to achieve that with createElement, appendChild or insertBefore/After.
推荐答案
.insertBefore和.firstChild
您可以在每个锚点的第一个子节点之前插入新的输入元素:
.insertBefore, and .firstChild
You could insert your new input element before the first child of each anchor:
// Gather up a reference to all anchors
var anchors = document.getElementsByTagName("a"), inputEl;
// Cycle over all of them
for ( var i = 0; i < anchors.length; i++ ) {
// Create a new input field
inputEl = document.createElement("input");
// Insert it before the first child of the anchor
anchors[i].insertBefore( inputEl, anchors[i].firstChild );
}
演示: http://jsbin.com/ibugul/edit#javascript,html
或者您可以使用替换
方法:
var a = document.getElementsByTagName("a"),
c = a.length;
while ( c-- ) {
a[c].innerHTML = a[c].innerHTML.replace( /(.*)/, function( s, c2 ){
return "<input />" + c2;
});
}
修改.innerHTML
Modify .innerHTML
var a = document.getElementsByTagName("a"),
c = a.length;
while ( c-- ) a[c].innerHTML = "<input />" + a[c].innerHTML;
jQuery
如果你已经在您的网站上使用 jQuery ,您可以使用它来缩短它:
jQuery
If you're already using jQuery on your site, you could use that to make this even shorter:
$("a").prepend("<input />");
注意,不值得为此包含库。
Note, it is not worth including the library just for this.
这篇关于使用Javascript在内容之前添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文