我正在尝试在行开始之前在标题区域中放置一个带有一些文本的div ...
创建元素并添加textnode并附加代码:
let newDiv = document.createElement('div');
newDiv.className = 'Hello';
newDiv.id = 'HelloId';
newDiv.setAttribute('title', 'This Is Test');
let chNode = document.createTextNode('Something is Here');
newDiv.appendChild(chNode)
newDiv.style.background = 'red';
newDiv.style.padding = '2%';
let headContainer = document.querySelector('header .container');
let headh1 = document.querySelector('header h1');
headContainer.insertBefore(newDiv, headh1)
console.log(headh1)
在HTML中看起来像
<header id="main-header" class="bg-success text-white p-4 mb-3">
<div class="container">
<div class="row">
<div class="col-md-6">
<h1 id="header-title">Item Lister</h1>
</div>
<div class="col-md-6 align-self-center">
<input type="text" class="form-control" id="filter" placeholder="Search Items...">
</div>
</div>
</div>
</header>
但是我遇到了错误
未捕获的DOMException:无法在“节点”上执行“ insertBefore”:要在其之前插入新节点的节点不是该节点的子节点。
答案 0 :(得分:0)
这是您的意思吗?在标题之前插入div吗?
let newDiv = document.createElement('div');
newDiv.className = 'Hello';
newDiv.id = 'Hello Id';
newDiv.setAttribute('tile', 'This Is Test');
let chNode = document.createTextNode('Something is Here');
newDiv.appendChild(chNode)
newDiv.style.background = 'red';
newDiv.style.padding = '2%';
let container = document.querySelector('header > .container')
let headh1 = container.querySelector('h1');
console.log(headh1)
headh1.closest("div").insertBefore(newDiv, headh1)
<header id="main-header" class="bg-success text-white p-4 mb-3">
<div class="container">
<div class="row">
<div class="col-md-6">
<h1 id="header-title">Item Lister</h1>
</div>
<div class="col-md-6 align-self-center">
<input type="text" class="form-control" id="filter" placeholder="Search Items...">
</div>
</div>
</div>
</header>
还是在行前?
let newDiv = document.createElement('div');
newDiv.className = 'Hello';
newDiv.id = 'Hello Id';
newDiv.setAttribute('tile', 'This Is Test');
let chNode = document.createTextNode('Something is Here');
newDiv.appendChild(chNode)
newDiv.style.background = 'red';
newDiv.style.padding = '2%';
let container = document.querySelector('header > .container')
let headh1 = container.querySelector('h1');
let row = headh1.closest(".row")
container.insertBefore(newDiv, row)
<header id="main-header" class="bg-success text-white p-4 mb-3">
<div class="container">
<div class="row">
<div class="col-md-6">
<h1 id="header-title">Item Lister</h1>
</div>
<div class="col-md-6 align-self-center">
<input type="text" class="form-control" id="filter" placeholder="Search Items...">
</div>
</div>
</div>
</header>