gpt4 book ai didi

javascript - 将具有特定 id 的 div 复制到具有相关 id 的目标

转载 作者:行者123 更新时间:2023-12-03 07:21:30 25 4
gpt4 key购买 nike

如何将具有特定类或特定 id 开头的所有 div 中的内容复制到一堆具有相关 id 的 div 中?我找到的例子并没有经过多份复制。我有一个工作正常的解决方案,但我不想使用 id 调用每个副本,而是希望使逻辑更好。

这就是我现在拥有的。

HTML( Handlebars 模板)

<!-- the id comes from handlebar content. There are many like this -->

<pre><code id="target-example-01" class='language-markup'></code></pre>

<!-- this content is put to place once handlebars has rendered the page -->
<div id="code-examples" style="display: none;">
<div class='code-example' id="source-example-01">
this is my a code example... there are many like me...
</div>
</div>

Javascript

var source = document.getElementById('source-example-01').innerHTML;
var target = document.getElementById('target-example-01');
if (target) target.innerHTML=source;

这工作正常,但我有 100 个示例,所以我不希望仅仅为了复制内容而手动维护 300 行代码。如何遍历所有具有“代码示例”类的 div,并将其内容复制到具有匹配 id 的 div。所有源 div 都将具有 id="source-(example-identifier)",所有目标 div 将具有 id="target-(example-identifier)"。我想如果代码会遍历 id 以“source-”开头的所有项目,则不需要该类

最佳答案

我会是老派并坚持使用 getElementsByClassName() 但由于问题是如何定位 div 将具有 id="target-(example-identifier) 你可以使用 querySelectorAll()

document.querySelectorAll('div[id^="source-example-"]')

有关的更多信息querySelectorAll()

Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors. The object returned is a NodeList.

因此输出非常类似于使用 getElementsByClassName()

如果您有任何疑问,请在下面留言,我会尽快回复。

How to target a specific tag with a class and id?

document.querySelectorAll('div.code-example[id^="source-example-"]')

您仍然需要循环遍历内容,就像按类名返回元素一样,但此查询选择器将仅返回具有类名 code-example 并包含 的 div 元素id 属性中的 source-example-

function QuerySelector() {
var Selector=document.querySelectorAll('div.code-example[id^="source-example-"]');
for(var i=0; i<Selector.length; i++){
alert(Selector[i].innerHTML);
}
}
<div class="code-example" id="source-example-01">Content Line One. - with class and id </div>
<div class="code-example">Content Line Two. - with correct class but no ID</div>
<div class="code-example" id="source-example-02">Content Line Three. - with class and id </div>
<button onclick="QuerySelector()">Get</button>

我希望这有帮助。快乐编码!

关于javascript - 将具有特定 id 的 div 复制到具有相关 id 的目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36196813/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com