gpt4 book ai didi

JavaScript:返回包含您定位的标签的innerHTML?

转载 作者:行者123 更新时间:2023-12-04 07:46:09 24 4
gpt4 key购买 nike

JS 新手。我无法在 Stacks 中找到答案,所以我希望这不是重复。我正在尝试返回标签的 innerHTML,包括我定位的标签。假设你有这个 HTML:

<div class="parent">
<p>Text 1</p>
<p>Text 2</p>
<p>Text 3</p>
</div>
而这个JS:
const divInner = document.querySelector('.parent').innerHTML
console.log(divInner)
控制台日志将仅返回 div 标签内的 html:
  <p>Text 1</p>
<p>Text 2</p>
<p>Text 3</p>
有没有办法返回父标签(div)的innerHTML INCLUSIVE,以便控制台日志返回整个部分,而无需在div之外创建另一个父容器?:
<div class="parent">
<p>Text 1</p>
<p>Text 2</p>
<p>Text 3</p>
</div>
我知道我可以做到这一点,如果我只是在内部 div 之外添加另一个父 div 并以父 div 的 innerHTML 为目标,但我正在尝试将它应用到添加更多 div 会搞乱对齐/间距的页面上,我不这样做如果我可以避免它,我不想重新调整它。

最佳答案

是的,您可以使用 outerHTML 来完成。 .

The outerHTML attribute of the element DOM interface gets the serialized HTML fragment describing the element including its descendants. It can be set to replace the element with nodes parsed from the given string.



const divInner = document.querySelector('.parent').outerHTML;
console.log(divInner);
<div class="parent">
<p>Text 1</p>
<p>Text 2</p>
<p>Text 3</p>
</div>

关于JavaScript:返回包含您定位的标签的innerHTML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67184822/

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