![](/img/trans.png)
[英]Is there a way to get a reference to all the paragraphs or headings in a web page in JavaScript?
[英]Converting all headings of a page into a list
現在,我正在使用一些非常基本的jQuery(不要討厭我)。 我的目標是將頁面的每個h3 / h4標頭轉換為列表,以進行“自創建”側邊欄導航。
例如:
<h3>This is a header</h3>
<h4>This is its subheader</h4>
<p>Here's some explanation.<p>
<h4>This is another subheader</h4>
<p>Here's some explanation.<p>
<h3>Here is a new header</h3>
<h4>With</h4>
<p>Here's some explanation.<p>
<h4>some</h4>
<p>Here's some explanation.<p>
<h4>other</h4>
<p>Here's some explanation.<p>
<h4>subheaders</h4>
<p>Here's some explanation.<p>
成:
<ul>
<li>This is a header
<ul>
<li>This is its subheader</li>
<li>This is another subheader</li>
</ul>
</li>
<li>Here is a new header
<ul>
<li>With</li>
<li>some</li>
<li>new</li>
<li>subheaders</li>
</ul>
</li>
</ul>
到目前為止,我所做的是:
//Selecting all existing Headers and Subheaders of the content wrapper
var headers = $('.some-text-wrapper h3, .some-text-wrapper h4');
//Placing them into a new div (later sidebar)
$('#headings').html(headers);
//Looping through each element trying to replace the tags
$('#headings h3, #headings h4').each(function(){
if ( $(this).is(':first-child') ) {
$(this).replaceWith('<ul><li>' + $(this).html() +'<ul>')
} else if ( $(this).prop("tagName") == 'H3' ) {
$(this).replaceWith('</ul></li><li>' + $(this).html() +'<ul>')
} else {
$(this).replaceWith('<li>' + $(this).html() +'</li>')
}
});
不幸的是,我最終遇到了一些麻煩,例如:
<ul>
<li>This is a header
<ul></ul>
</li>
</ul>
<li>This is its subheader</li>
當涉及到h3標題時,我就沒有繼續進行整理標簽等的工作。我不知道ul / li標簽的自動關閉是由jQuery替換還是由Wordpress引起的(有些自動關閉標簽的問題)。
我知道我可以簡單地使用創建的h3 / h4元素並將它們設置為列表樣式,但這並不是我真正想要的。 無論如何,我有興趣為此尋找解決方案。
提前致謝。
您可以使用jquery的nextuntil
( https://api.jquery.com/nextUntil/ )並將其傳遞給選擇器和過濾器以創建適當的列表。
var output = ""; $("h3").each(function(){ output += "<li>" + $(this).text() + "</li>"; if($(this).next("h4").length > 0){ output += "<ul>"; $(this).nextUntil("h3","h4").each(function(){ output += "<li>" + $(this).text() + "</li>"; }); output += "</ul>"; } }); $("#list").html(output);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <h3>This is a header</h3> <h4>This is its subheader</h4> <p>Here's some explanation.<p> <h4>This is another subheader</h4> <p>Here's some explanation.<p> <h3>Here is a new header</h3> <h4>With</h4> <p>Here's some explanation.<p> <h4>some</h4> <p>Here's some explanation.<p> <h4>other</h4> <p>Here's some explanation.<p> <h4>subheaders</h4> <p>Here's some explanation.<p> <div id="list"><ul></ul></div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.