[英]How to change Header to an H3 if it nested inside an H2 through a Script?
I have this component called topComponent that has a title
, body, and link.我有一个名为topComponent的组件,它有一个title
、正文和链接。 The Title is an H2.标题是 H2。
<div class="topComponent">
<div class="Wrapper">
<h2 class="title">About The Eartht</h2>
<div class="container htmlText">
<p>Here is some information about the Earth..</p>
</div>
<div class="infoLink">
<a href="........." target="_blank"</a>
</div>
</div>
</div>
However, if this title
header is nested inside another header that is an H2, then I am trying make this title
header an h3.但是,如果这个title
header 嵌套在另一个 H2 的 header 中,那么我正在尝试使这个title
header 成为 h3。 Basically let say there is an HTML like this:基本上可以说有一个像这样的 HTML:
<h2 class="bigHeader">About The Eartht</h2> // Parent Header
<div class="topComponent">
<div class="Wrapper">
<h2 class="title">About The Eartht</h2>
<div class="container htmlText">
<p>Here is some information about the Earth..</p>
</div>
<div class="infoLink">
<a href="........." target="_blank"</a>
</div>
</div>
</div>
Here, there is a parent header called bigHeader
that is an H2.在这里,有一个名为bigHeader
的父 header 是一个 H2。 So in this case, I want the title
header to change to H3 instead of h2, since there is already a parent h2 on top.所以在这种情况下,我希望title
header 更改为 H3 而不是 h2,因为顶部已经有一个父 h2。
Question: How can we determine if the title
should be an h2 or h3 depending on if there was an H2 parent for this element through a script?问题:我们如何通过脚本根据该元素是否有 H2 父级来确定title
应该是 h2 还是 h3?
I was thinking maybe to use the $(this).closest(":header").text()
to find out what the parent header is, but I am not sure if that's the best approach?我在想也许可以使用$(this).closest(":header").text()
来找出父 header 是什么,但我不确定这是否是最好的方法?
This is maybe what you are trying to achieve.这可能是您想要实现的目标。 You need to have a particular selector.您需要有一个特定的选择器。 I have taken the given example but for your scenario, you need to have a strong selector.我已经举了给定的例子,但对于你的场景,你需要一个强大的选择器。
$(document).ready(function(e){ var cnt = 0; $("h2").each(function(){ if(cnt > 0) { $(this).replaceWith($('<h3>' + this.innerHTML + '</h3>')); } cnt++; }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h2 class="bigHeader">About The Eartht 1</h2> // Parent Header <div class="topComponent"> <div class="Wrapper"> <h2 class="title">About The Eartht</h2> <div class="container htmlText"> <p>Here is some information about the Earth..</p> </div> <div class="infoLink"> <a href="........." target="_blank"</a> </div> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.