2017-01-25 66 views
0

比方說,我有以下文件:如何獲得給定元素值的DOM元素的唯一CSS選擇器?

<html> 
    <body> 
    <h1>Hello world</h1> 
    </body> 
</html> 

由於字符串「Hello World」,我怎麼能搜索文檔,並生成正確的元素的CSS選擇器(在這種情況下,H1)?

+0

':contains('Hello world')' –

+0

您必須使用jQuery。沒有辦法使用標準的CSS:https://www.w3.org/TR/css3-selectors/#selectors – jwerre

回答

2

好的,這是sl - - 如果你使用$(「:contains」),你會得到整個樹到最內層的元素。使用這個,你可以找到最內層的節點。

var myContainer = $(":contains('Hello world') "); 
 

 
while(myContainer.children().length != 0) { 
 
    myContainer =myContainer.children(); 
 
} 
 
myContainer.addClass("foo");
.foo { 
 
    border: 1px dotted blue; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<html> 
 
    <body> 
 
    <h1>Hello world</h1> 
 
    </body> 
 
</html>

或者,做同樣的事情用一個單一的選擇:

$(":contains('Hello world'):not(:has(*))").addClass("foo");
.foo { 
 
    border: 1px dotted blue; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="content-pane"> 
 
<div class="header-pane"> 
 
<h1>Hello world</h1> 
 
</div> 
 
<div class="inner-content"> 
 
<h2> 
 
Hello world is me! 
 
</h2> 
 
</div> 
 
</div>

0

如果你不使用尋找一個純JavaScript的答案庫可以使用DOM操作/遍歷。

我已經修改了這個代碼片段,它被設計用來遍歷一個節點樹並以字符串形式返回文本內容。 https://gist.github.com/padolsey/3033511

function getText(node) { 

if (node.nodeType === 3) { 
    return node.data; 
} 

var txt = ''; 

if (node = node.firstChild) do { 
    txt += getText(node); 
} while (node = node.nextSibling); 

return txt; 

}

function checkNode(node) { 
 

 
    if (node.nodeType === Node.TEXT_NODE) { 
 
    var expr= "Hello World"; 
 
    if (node.textContent.indexOf(expr) >= 0) { 
 
     node.parentNode.className = "foo"; 
 
    } 
 
    } 
 

 
    if (node = node.firstChild) { 
 
    //set to next child and continue if it exists 
 
    do { 
 
     checkNode(node); 
 
    } while (node = node.nextSibling); //while has sibilings 
 
} 
 

 
} 
 
checkNode(document.body)
.foo { 
 
    color: red; 
 
}
<div> 
 

 
    <h1>Hello World</h1> 
 

 
    <p>Hello World</p> 
 

 
    <h1>Hlelo Wrldo</h1> 
 

 
</div>

我想出了一些研究,領導讓我從詹姆斯Padolsey這個博客帖子後,此解決方案:Replacing text in the DOM… solved?他談到穿越元素的困難準確地獲取它們包含的文本,因爲向用戶顯示的文本可能會散佈在像這樣的幾個子元素上:

<p> 
    This is a <span class="f">te<em>st</em></span>. 
</p> 

該博客文章的主要議題是替代文本和他創造的怎麼做,同時尊重奇怪嵌套如上圖所示一個很好的例子。如果你對沒有圖書館的更強大的解決方案感興趣,我建議給他的文章讀一讀。這雖然有些古老,但最後的作品還是基於我提供的同樣要求。