将元素追加为元素之后的兄弟元素?

时间:2014-01-29 04:47:38

标签: javascript html dom

如何使用纯Javascript在HTML元素后添加文本?有appendChild但是这会在元素中添加它。我想把它添加为像这样的元素之后的兄弟姐妹:

<img id="myimg" src="..." />

<script>
  var myimg = document.getElementById('myimg');
  myimg.appendAFTER('This is my caption.'); //pseudo-code and doesn't really work
</script>

我想最终得到这个:

<img id="myimg" src="..." />
This is my caption.

来自jQuery的after()的Javascript等效项是什么?

3 个答案:

答案 0 :(得分:16)

结帐Node.insertBefore()Node.nextSiblingfiddle):

var myimg = document.getElementById('myimg');
var text = document.createTextNode("This is my caption.");
myimg.parentNode.insertBefore(text, myimg.nextSibling)

Element.insertAdjacentHtml()fiddle):

var myimg = document.getElementById('myimg');
myimg.insertAdjacentHTML("afterend", "This is my caption.");

答案 1 :(得分:1)

请使用以下代码:

<img id="myimg" src="..." />

<script>
  var myimg = document.getElementById('myimg');
  var txt=document.createElement("span");
  txt.innerHTML="Whatever text you want to write . . .";
  if(myimg.nextSibling){
    myimg.parentNode.insertBefore(txt,myimg.nextSibling);
  }else{
    myimg.parentNode.appendChild(txt);
  }
</script>

答案 2 :(得分:-2)

如何使用jQuery .after():

<强> jquery的

<script>
      $('#myimg').after('<p>This is my caption!</p>');
</script

<强>的JavaScript

<script>
  var myimg = document.getElementById('myimg');
  var new_node = document.createElement("p");
  new_node.innerHTML = "This is my Caption!";
  myimg.parentNode.insertBefore(new_node,myimg.nextSibling);
</script>

这是小提琴:http://jsfiddle.net/sunnykumar08/6cnSz/ HTH!