[英]Getting a HTML element DOM as string using javascript without child elements
[英]Pure JavaScript - edit text in DOM element without touching child elements
我目前正在嘗試編輯單個父元素的所有子元素的文本。 該結構類似於以下內容:
<section id=emoji>
<h1>Emojies</h1>
<p id=ea1>:-)</p>
<p id=ea2>(TM)</p>
<p id=ea3>Trademark(TM) <span>:-</span>)</p>
<p id=ea4>Do you <3 me?</p>
<p id=ea5>:-):-):-)<3<3<3</p>
</section>
如您所見,第三段標記具有span標記。 我有一個函數,它將使用給定的字符串並將表情符號的所有實例轉換為emojify函數中的指定表情。 我想動態地對本節中的這些元素執行相同的操作。 問題是我不想編輯span ,並且在一分鍾之內,合並span標簽會生成一張笑臉,這是我不想做的。
我的表情符號功能如下所示:
function emojify(str) {
let emojies = [];
emojies['(TM)'] = '™️';
emojies['<3'] = '❤️';
emojies[':-)'] = '😀';
emojies.forEach(function(el) {
if (str.indexOf(el) > -1) {
str = str.split(el).join(emojies[el]);
}
});
return str;
}
這是我目前嘗試動態執行的功能:
function pageEmojify(selector) {
let element = document.querySelector(selector);
element.childNodes.forEach(function(el) {
el.textContent = emojify(el.textContent);
});
}
它有效,我只需要在任何轉換中不包含span標簽即可。
我在StackOverflow上查看了各種問題,但是似乎所有問題都使用了jQuery,但我不想將其用於該特定問題。
我如何編輯我的pageEmojify函數來做到這一點?
function emojify(str) { let emojies = []; emojies['(TM)'] = '™️'; emojies['<3'] = '❤️'; emojies[':-)'] = '😀'; for (let el of Object.keys(emojies)) { if (str && str.indexOf(el) > -1) { str = str.split(el).join(emojies[el]); } } return str; } function pageEmojify(selector) { let element = document.querySelector(selector); element.childNodes.forEach(function(el) { if (el.childNodes) { el.childNodes.forEach(function(elm) { elm.nodeValue = emojify(elm.nodeValue) }) } else el.textContent = emojify(el.textContent); }); } pageEmojify('section');
<section id='emoji'> <h1>Emojies</h1> <p id='ea1'>:-)</p> <p id='ea2'>(TM)</p> <p id='ea3'>Trademark(TM) <span>:-</span>)<span>:-</span>)</p> <p id='ea4'>Do you <3 me?</p> <p id='ea5'>:-):-):-)<3<3<3</p> </section>
檢查節點的nodeValue
以獲得給定元素的值。 如果還有其他節點,則遍歷該數組以獲取所有其他節點的內容。
如果您檢入頁面的屬性(在chrome dev工具中,轉到元素,單擊一個元素,然后查看右側的屬性),則可以看到每個頁面中都有一個“文本”節點
元素。 如果是
元素whoc中有span,它將顯示其中包含3個元素-文本,span和一個文本。 您可以修改其功能以僅處理其中的文本節點。 就像
function pageEmojify(selector) {
let element = document.querySelector(selector);
element.childNodes.forEach(function(el) {
## get child nodes of e
## if teh childnode is of type text, then get innertext and pass it to emojify
});
}
我在這里提供偽代碼,因為我不是js函數專家。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.