簡體   English   中英

給定元素的值,如何為DOM元素獲得唯一的CSS選擇器?

[英]How can I get a unique CSS Selector for a DOM element given the element's value?

假設我有以下文檔:

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

給定字符串“ Hello world”,我如何搜索文檔並為正確的元素(在本例中為h1)生成CSS選擇器?

好的,這很草率-如果使用$(“: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> 

如果您在不使用庫的情況下尋找純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> 

經過一些研究,我想到了James Padolsey的博客文章,提出了這種解決方案: 替換DOM中的文本...解決了嗎? 他談到了遍歷元素以准確獲取其包含的文本的困難,因為向用戶顯示的文本可能分布在幾個子元素上,如下所示:

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

該博客文章的主題是替換文本,他創建了一個很好的示例,說明了如何在尊重奇怪的嵌套的同時做到這一點,如上所示。 如果您對不包含庫的更健壯的解決方案感興趣,建議您閱讀他的文章。 它有些陳舊,但最終他的榜樣還是有效的,並且基於我提供的相同要旨。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM