简体   繁体   English

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

[英]JavaScript: Return innerHTML inclusive of the tag you're targeting?

New to JS. JS新手。 I was unable to find an answer to this in the Stacks, so I hope it's not a repeat.我无法在 Stacks 中找到这个问题的答案,所以我希望它不会重复。 I'm trying to return the innerHTML of a tag, inclusive of the tag I'm targeting.我正在尝试返回标签的 innerHTML,包括我要定位的标签。 Let's say you have this HTML:假设你有这个 HTML:

<div class="parent">
  <p>Text 1</p>
  <p>Text 2</p>
  <p>Text 3</p>
</div>

And this JS:而这个JS:

const divInner = document.querySelector('.parent').innerHTML
console.log(divInner)

The console log will return only the html inside of the div tags:控制台日志将仅返回 div 标签内的 html:

  <p>Text 1</p>
  <p>Text 2</p>
  <p>Text 3</p>

Is there a way to return the innerHTML INCLUSIVE of the parent tag (the div), so that the console log returns this entire section, without creating another parent container outside of the div?:有没有办法返回父标记(div)的innerHTML INCLUSIVE,以便控制台日志返回整个部分,而不在div之外创建另一个父容器?:

<div class="parent">
  <p>Text 1</p>
  <p>Text 2</p>
  <p>Text 3</p>
</div>

I know I can do this if I just add another parent div outside the inner div and target the parent div's innerHTML instead, but I'm trying to apply this on a page where adding more divs will screw up the alignment / spacing and I don't wish to readjust it all over again if I can avoid it.我知道如果我只是在内部 div 之外添加另一个父 div 并以父 div 的 innerHTML 为目标,我可以做到这一点,但我试图在添加更多 div 会搞砸 alignment / 间距的页面上应用它,我不如果我能避免的话,我不想重新调整它。

Yes, you can do it using outerHTML .是的,您可以使用outerHTML来做到这一点。

The outerHTML attribute of the element DOM interface gets the serialized HTML fragment describing the element including its descendants.元素 DOM 接口的outerHTML属性获取描述元素及其后代的序列化 HTML 片段。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM