比方说,我有以下文件:如何获得给定元素值的DOM元素的唯一CSS选择器?
<html>
<body>
<h1>Hello world</h1>
</body>
</html>
由于字符串“Hello World”,我怎么能搜索文档,并生成正确的元素的CSS选择器(在这种情况下,H1)?
比方说,我有以下文件:如何获得给定元素值的DOM元素的唯一CSS选择器?
<html>
<body>
<h1>Hello world</h1>
</body>
</html>
由于字符串“Hello World”,我怎么能搜索文档,并生成正确的元素的CSS选择器(在这种情况下,H1)?
好的,这是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>
如果你不使用寻找一个纯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>
该博客文章的主要议题是替代文本和他创造的怎么做,同时尊重奇怪嵌套如上图所示一个很好的例子。如果你对没有图书馆的更强大的解决方案感兴趣,我建议给他的文章读一读。这虽然有些古老,但最后的作品还是基于我提供的同样要求。
':contains('Hello world')' –
您必须使用jQuery。没有办法使用标准的CSS:https://www.w3.org/TR/css3-selectors/#selectors – jwerre