我需要一个简单的解决方案来获取包含给定文本的DOM标记。
例如
<body>
<div id='example'>Hello world!</div>
</body>
<script>
function GetTagInfo('Hello');
//I wan't it to return the div as the object so I'll next update the //content with another text.
</script>
我不想使用任何正则表达式,我需要干净简单的代码。
答案 0 :(得分:3)
您可以使用包含选择器:
$('body *:contains("specified text")')//return div element(s) that contains specified text
但是包含不适用于严格比较。对于严格比较,您需要使用过滤功能:
$('body *').filter(function(){
return $(this).text() == "specified text";
});
答案 1 :(得分:0)
你可以试一试:
function finder(query) {
// get all elements
var elements = document.getElementsByTagName('*');
var out = [];
for (var i = 0, l = elements.length; i < l; i++) {
// if the element isn't a script and doesn't contain any child
// elements and the text contains whatever you passed
// in as a query, add it to the out-going array
if (elements[i].tagName !== 'SCRIPT'
&& !elements[i].children.length
&& elements[i].textContent.indexOf(query) > -1) {
out.push(elements[i]);
}
}
return out;
}
// call finder with the parameter you want
var arr = finder('Hello');
// call the update function with the array
// passed back from finder
updateDom(arr);
function updateDom(arr) {
// loop over the elements array from finder
// and change the contents
for (var i = 0, l = arr.length; i < l; i++) {
arr[i].textContent = 'Hello Mikołaj Król';
}
}
请注意textContent
是IE9 +。