記事の概要
htmlタグ混在のテキストをhtmlタグとプレーンテキストで分けるJavaScriptコード
作成日:2025-06-20
最終更新日:2025-06-20
記事の文字数:2162
本記事のトピック
- 概要
- JavaScriptコード
htmlタグ混在のテキストをhtmlタグとプレーンテキストで分けるJavaScriptコード
概要
「よくある質問は<a href="/">こ<span>ち</span>ら</a>です」 というようなhtmlタグ混在のテキストを、htmlタグとプレーンテキストごとに分けるJavaScriptコードです。
「よくある質問は<a href="/">こ<span>ち</span>ら</a>です」 であれば、以下のような出力になります。
const htmlText = よくある質問は<a href="/">こ<span>ち</span>ら</a>です;
const separatedHtmlText = separateHtmlText(htmlText);
console.log(separatedHtmlText);
//[
// {
// "htmlText": "よくある質問は",
// "type": "text",
// "tag": null
// }, {
// "htmlText": "<a href=\"/\">",
// "type": "tagOpen",
// "tag": "a"
// }, {
// "htmlText": "こ",
// "type": "text",
// "tag": null
// }, {
// "htmlText": "<span>",
// "type": "tagOpen",
// "tag": "span"
// }, {
// "htmlText": "ち",
// "type": "text",
// "tag": null
// }, {
// "htmlText": "</span>",
// "type": "tagClose",
// "tag": "span"
// }, {
// "htmlText": "ら",
// "type": "text",
// "tag": null
// }, {
// "htmlText": "</a>",
// "type": "tagClose",
// "tag": "a"
// }, {
// "htmlText": "です",
// "type": "text",
// "tag": null
// }
//]
JavaScriptコード
実際のJavaScriptコードは以下です。
function separateHtmlText(htmlText){
const htmlTextElm = new DOMParser().parseFromString(htmlText, 'text/html').body;
const results = separateNode(htmlTextElm);
return(results);
}
function separateNode(nodes){
const results = [];
for (const child of nodes.childNodes) {
if (child.nodeType === Node.TEXT_NODE) {
// プレーンテキスト
results.push(createSeparateObj(child.textContent, 'text'));
} else if (child.nodeType === Node.ELEMENT_NODE) {
// タグ開始
const tagName = child.tagName.toLowerCase();
const tagAttrs = [...child.attributes].map(attr => `${attr.name}="${attr.value}"`).join(' ');
const tagOpen = `<${tagName}${tagAttrs ? ' ' + tagAttrs : ''}>`;
const tagClose = `${child.tagName.toLowerCase()}>`;
results.push(createSeparateObj(tagOpen, 'tagOpen', tagName));
const r = separateNode(child);
results.push(...r);
results.push(createSeparateObj(tagClose, 'tagClose', tagName));
}
}
return results;
function createSeparateObj(htmlText, type, tag = null){
const result = {
text: htmlText,
type: type,
tag: tag,
};
return result;
}
}
上にも書いてありますが、基本的な使い方は以下です。
const htmlText = よくある質問は<a href="/">こ<span>ち</span>ら</a>です;
const separatedHtmlText = separateHtmlText(htmlText);
文字列ではなく、html要素自体を渡したい場合は以下で動くはずです。
const targetElm = document.getElementById('targetElmId')
const separatedHtmlText = separateNode(targetElm);
コメントログ
コメント投稿
管理人ツイート