javascript - 在特定位置添加创建的元素

标签 javascript html wordpress

我对编码还很陌生(2021 年 1 月),通过大量在线搜索,我已经取得了很大的进展,但目前我陷入了困境。

setTimeout(function(){

var supbtn = document.createElement("BUTTON");
supbtn.innerHTML = "Support";
supbtn.className = "Support-logout-class";
supbtn.onclick = function(){window.open("LinkToSite","_blank")}; 

document.body.appendChild(supbtn);

}, 2000);

我工作的公司使用了一个默认的 WordPress 插件,由于我们正在为此用例构建自定义网站,因此我们希望尝试升级当前的插件。 (到目前为止已经取得了很多成功)

基本上有一个默认代码,我想在特定位置添加上述“按钮”元素,目前它添加在“主体”内部,效果完美!

我想放置它的代码:

<div class="wpws-webinar-summary-content sc-iBEsjs sJWcq">
<div class="sc-fZwumE cyVGPD"></div>
<div class="wpws-webinar-summary-logout sc-gmeYpB fOXvtE">
<svg class="wpws-33" focusable="false" viewBox="0 0 24 24" aria-hidden="true" role="presentation" title="Verlaat het webinar"><path fill="none" d="M0 0h24v24H0z"></path>
<path d="M10.09 15.59L11.5 17l5-5-5-5-1.41 1.41L12.67 11H3v2h9.67l-2.58 2.59zM19 3H5c-1.11 0-2 .9-2 2v4h2V5h14v14H5v-4H3v4c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"></path>
</svg>
</div>
</div>

我希望生成的按钮出现在:class="wpws-webinar-summary-logout"之前 (为什么之前?因为如果我是对的,则代码“”未设置,因为它可以在页面之间更改。而且我确信“wpws-webinar-summary-logout”不会更改)

但我似乎找不到合适的搜索词, 当我认为我已经很接近时,我似乎还不太明白。

有人可以给我任何提示、技巧、例子吗?

提前非常感谢! 格。伊恩

最佳答案

您可以使用insertBefore()在另一个元素之前插入一个元素,例如:

setTimeout(function(){

  // Create button element
  var supbtn = document.createElement("BUTTON");
  supbtn.innerHTML = "Support";
  supbtn.className = "Support-logout-class";
  supbtn.onclick = function(){window.open("LinkToSite","_blank")};

  // Find the element that we'll use as reference to inject our button
  var webinar_summary_logout = document.querySelector('.wpws-webinar-summary-logout');
  
  // Get the parent element
  var parentDiv = webinar_summary_logout.parentNode;
  
  // Inject the button before our referenced element
  parentDiv.insertBefore(supbtn, webinar_summary_logout);

}, 2000);
<div class="wpws-webinar-summary-content sc-iBEsjs sJWcq">
  <div class="sc-fZwumE cyVGPD"></div>

  <div class="wpws-webinar-summary-logout sc-gmeYpB fOXvtE">
    <svg class="wpws-33" focusable="false" viewBox="0 0 24 24" aria-hidden="true" role="presentation" title="Verlaat het webinar"><path fill="none" d="M0 0h24v24H0z"></path>
      <path d="M10.09 15.59L11.5 17l5-5-5-5-1.41 1.41L12.67 11H3v2h9.67l-2.58 2.59zM19 3H5c-1.11 0-2 .9-2 2v4h2V5h14v14H5v-4H3v4c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"></path>
    </svg>
  </div>
</div>

关于javascript - 在特定位置添加创建的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66856225/

相关文章:

javascript - Vue-chartjs:即使数据没有改变也重新渲染图表

javascript - typescript 的 Node.js process.stdin 问题(tty.ReadStream 与 ReadableStream)

javascript - 如何在 Angular 2/Ionic 2 中使用插值创建链接标签

javascript - 响应式选项卡 - Wordpress

html - Css:Wordpress 和 Bootstrap:设置帖子页面特色图片的样式

javascript - 如何编写一个函数来创建一定长度的对象数组?对象具有自定义生成的数据

javascript - 如何将下拉菜单保持在 ActiveX 之上

javascript - 单击选项卡无法准确工作

html - CSS 导航垂直对齐

mysql - WordPress 多数据库