我正在使用wordpress,我想在页面上使用Javascript添加一些HTML代码.我不想制作子主题然后编辑php文件.这是有风险的,我不知道关于PHP.
我想添加一个兄弟div.这是默认的示例代码.
<div class="div1">
<div class="div1inside">
Text
</div>
</div>
<div class="div2">
<div class="div2inside">
Text
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
现在我想在div1和div2之间添加我的自定义div及其内部html.
<div class="mydiv">
<div class="mydivinside">
Text
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
请告诉我如何使用Javascript.
有(至少)两种方式,第一种方式:
// document.querySelector() finds, and returns, the first element
// matching the supplied selector (or null, if no element is found):
var el1 = document.querySelector('.div1');
// here we create an adjacent element from the string of HTML,
// the 'afterend' argument states that this adjacent element
// follows the el1 node, rather than preceding it or appearing
// within:
el1.insertAdjacentHTML('afterend', '<div class="mydiv"><div class="mydivinside">Text</div></div>');
Run Code Online (Sandbox Code Playgroud)
var div1 = document.querySelector('.div1');
div1.insertAdjacentHTML('afterend', '<div class="mydiv"><div class="mydivinside">Text</div></div>');Run Code Online (Sandbox Code Playgroud)
<div class="div1">
<div class="div1inside">
Text
</div>
</div>
<div class="div2">
<div class="div2inside">
Text
</div>
</div>Run Code Online (Sandbox Code Playgroud)
第二个你首先创建<div>要插入的,然后使用parentNode.insertBefore():
var htmlString = '<div class="mydiv "><div class="mydivinside">Text</div></div>',
// here we create a <div> element:
div = document.createElement('div'),
// we retrieve the element after which the new
// element should be inserted:
div1 = document.querySelector('.div1');
// assign the supplied HTML string to the innerHTML of the
// created element:
div.innerHTML = htmlString;
// and use parentNode.insertBefore to insert the desired element
// (the first argument) before the element identified in the
// second argument, which is the nextSibling of the found
// 'div1' element:
div1.parentNode.insertBefore(div.firstChild, div1.nextSibling);
Run Code Online (Sandbox Code Playgroud)
var htmlString = '<div class="mydiv "><div class="mydivinside">Text</div></div>',
div = document.createElement('div'),
div1 = document.querySelector('.div1');
div.innerHTML = htmlString;
div1.parentNode.insertBefore(div.firstChild, div1.nextSibling);Run Code Online (Sandbox Code Playgroud)
<div class="div1">
<div class="div1inside">
Text
</div>
</div>
<div class="div2">
<div class="div2inside">
Text
</div>
</div>Run Code Online (Sandbox Code Playgroud)
参考文献:
document.createElement().document.querySelector().Element.insertAdjacentHTML().Node.firstChild.Node.insertBefore().Node.nextSibling.Node.parentNode.