通过指定文本获取标签

Get tag by specified text

我需要一个简单的解决方案来获取包含给定文本的 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>

我不想使用任何正则表达式,我需要简洁明了的代码。

您可以使用包含选择器:

$('body *:contains("specified text")')//return div element(s) that contains specified text

但是包含不适用于严格比较。严格比较需要使用过滤函数:

$('body *').filter(function(){
    return $(this).text() == "specified text";
});

你可以试一试:

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+。

DEMO