[英]How to get header ID from the HTML/DOM using react and typescript
我有一個應用程序,它使用 marked.js 將一些 markdown 文件轉換為 html,並將轉換后的 HTML 顯示到 web 頁面。 在下面的代碼片段中,我遍歷文本節點以獲取顯示的所有原始文本值,將它們存儲在某個索引中,其中文本值對應於數字 id
// iterate over file objects which contain raw markdown
files.forEach(file => {
// convert file's markdown string to html string using marked.js
const htmlString = marked(file.markDown);
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
const walker = document.createTreeWalker(doc, NodeFilter.SHOW_TEXT);
// const walker = document.createTreeWalker(doc, NodeFilter.SHOW_ELEMENT);
let currentNode = walker.currentNode;
while (currentNode != null) {
if (currentNode.textContent != null) {
// index every HTML element's raw text value and assign it to an id
searchIndexReference.push({ id: id++, text: currentNode.textContent });
//console.log('currentNode');
//console.log(currentNode);
}
const nextNode = walker.nextNode();
if (nextNode != null) {
currentNode = nextNode;
} else {
break;
}
}
});
我想知道如何獲取 header id 值並將其也添加到索引中,直到遇到下一個 header id 。 這樣,searchIndexReference 會將文本值條目鏈接到它所在的 header。
假設我們下面有一些 HTML:
<h1 id="top-most-header">Top Most Header</h1>
<p>Here is some text 1</p>
<p>Here is some text 2</p>
<h2 id="some-other-section-header">Some Other Section Header</h1>
<p>Here is some text 3</p>
<p>Here is some text 4</p>
這些條目將像這樣附加到 searchIndexReference object。 (當前的 header id 值被存儲直到遇到下一個 header)
{id: 1, headerId: 'top-most-header', text: 'Top Most Header'}
{id: 2, headerId: 'top-most-header', text: 'Here is some text 1'}
{id: 3, headerId: 'top-most-header', text: 'Here is some text 2'}
{id: 4, headerId: 'some-other-section-header', text: 'Some Other Section Header'}
{id: 5, headerId: 'some-other-section-header', text: 'Here is some text 3'}
{id: 6, headerId: 'some-other-section-header', text: 'Here is some text 4'}
這也適用於嵌套元素,如 ul、li 等。
我知道什么時候我打印出 currentNode 使用
const walker = document.createTreeWalker(doc, NodeFilter.SHOW_ELEMENT);
它顯示完整的 HTML header 元素而不是 NodeFilter.SHOW_TEXT,但我不確定從那里到 go 的位置。
檢查父節點,如果它是 header 則保存 id
if(currentNode.parentNode.nodeName === 'H1') {
headerId = currentNode.parentNode.id
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.