[英]How to style only elements of a type that have not text nodes as siblings?
我有這個標記:
<div class="wysiwyg">
<em>It has to be red because is the only em element</em>
</div>
<div class="wysiwyg">
Some text
<em>Not to be red because has previous (and following) text node</em>
Some text
</div>
<div class="wysiwyg">
<em>It has to be red because its' a em in a div that has only ems and no text node / </em>
<em>It has to be red because its' a em in a div that has only ems and no text node</em>
我想應用element.style.color = "red";
僅對<ems>
元素是其父元素的唯一<em>
子元素,或具有其他<em>
作為同級元素,但沒有文本節點作為同級元素的元素。
另外,我想知道如何僅使用諸如node.style.color = blue;
類的樣式來設置文本節點的樣式node.style.color = blue;
(我知道.style
方法僅適用於元素...)。
謝謝!
假設您想要一個本機JavaScript解決方案,並且至少可以定位到EcmaScript 5,那么這里是一個解決方案https://jsfiddle.net/pjhuptt3/ 。
我正在使用childNodes
來獲取所有的子節點,包括文本節點。 另外,我正在檢查nodeType
是否等於3
(文本節點),並且必須檢查文本節點是否不是空格。
請注意,該代碼僅用於示例目的,用於演示您擁有的工具。 未經任何測試或優化。
function hasTextNodes(node) {
if (!node || !node.childNodes.length) return false;
for (var i=0;i<node.childNodes.length;++i) {
var child = node.childNodes[i];
// check if the node is text node and check if it's not a white space
if (child.nodeType == 3 && child.textContent && child.textContent.trim().length)
return true;
}
return false;
}
document.querySelectorAll(".wysiwyg").forEach(function(node) {
if (!hasTextNodes(node))
node.style.backgroundColor = "blue";
});
如果您想設置em
元素的樣式,則可以執行以下操作。
document.querySelectorAll(".wysiwyg").forEach(function(node) {
if (!hasTextNodes(node)) {
// query the em direct children
node.querySelectorAll("> em").forEach(function(em) {
em.style.backgroundColor = "blue";
});
}
});
為了完整起見,我應該告訴您,除非您需要這種精確的方案(例如,這是一些教育性的練習),否則有幾種更好的方法可以實現相同的目標。
span
並添加特定的類。 這樣一來,您可以更輕松地處理它們,可以選擇它們,設置其樣式等。 jQuery
的框架,這類任務非常容易解決,並且jQuery
本身並不會增加太多開銷,尤其是如果您使用CDN引用它時。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.