Append element in tag right before contents with Javascript

巧了我就是萌 提交于 2019-12-10 11:14:04

问题


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>
...

to code

<a><input/>Text 1</a>
<a><input/>Text 2</a>
<a><input/>Text 3</a>
...

I don't have a clue how to achieve that with createElement, appendChild or insertBefore/After.


回答1:


.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 );
}

Demo: http://jsbin.com/ibugul/edit#javascript,html

Regular Expression

Or you could use the replace method:

var a = document.getElementsByTagName("a"), 
    c = a.length;

while ( c-- ) {
  a[c].innerHTML = a[c].innerHTML.replace( /(.*)/, function( s, c2 ){
    return "<input />" + c2;
  }); 
}

Modify .innerHTML

var a = document.getElementsByTagName("a"), 
    c = a.length;

while ( c-- ) a[c].innerHTML = "<input />" + a[c].innerHTML;

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.




回答2:


It's not that hard :)

​(function() {
    var links = document.getElementsByTagName("a"),
        input,
        i = links.length;

    while (i--) {
        input = document.createElement("input");
        links[i].insertBefore(input, links[i].firstChild);
    }
}())​


来源:https://stackoverflow.com/questions/10657487/append-element-in-tag-right-before-contents-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!