使用本机javaScript附加html [英] Appending html using native javaScript

查看:43
本文介绍了使用本机javaScript附加html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用纯javaScript将一些html附加到现有元素上:

I need to append some html to an existing element using pure javaScript:

function create(htmlStr) {
  var frag = document.createDocumentFragment(),
    temp = document.createElement('div');
  temp.innerHTML = htmlStr;
  while (temp.firstChild) {
    frag.appendChild(temp.firstChild);
  }
  return frag;
}

var target = document.querySelectorAll(".container-right");
var fragment = create(
  '<div class="freetext"><p>Some text that should be appended...</p></div>'
);
document.body.insertBefore(fragment, document.body.childNodes[0]);

这是可行的,但是我有两个问题:

It's kind of working, but I have two questions:

  1. 如何确定html片段是通过类 container-right 而不是正文附加到div的?将最后一行更改为 document.body.insertBefore(fragment,target); 不起作用.

  1. How can I make sure that the html fragment is appended to the div with the class container-right and not just the body? Changing the last line to document.body.insertBefore(fragment, target); doesn't work.

如何在目标元素的内容之后-在现有内容之后-在jQuery的append()之类的之后插入html?

How can I insert the html after the content in the target element - after the existing content - like jQuery's append()?

非常感谢您的帮助.

JsFiddle此处.

推荐答案

好,我知道这可行:

let elem = document.querySelector ( 'css-selector (id or class)' )

那应该给你你的元素.然后,您可以这样做:

That should give you your element. Then you do this:

elem.innerHTML = elem.innerHTML + myNewStuff;

这会将您的html附加到该元素的innerHTML上.我很快尝试了一下,它起作用了.

That'll append your html to the innerHTML of the element. I tried it quickly, it works.

这篇关于使用本机javaScript附加html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆