Javascript - check if div contains a word?

后端 未结 8 1736
情话喂你
情话喂你 2020-12-25 11:32

How can I check if a div contains a certain word?

var divs= document.getElementsByTagName(\'div\');
for (var i = 0, len = divs.length; i < len; ++i) {

           


        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-25 11:53

    Gosh, so many answers!

    To get just the text of an element, the simple way is to use textContent or, where not supported, innerText. All browsers in use support one or the other (maybe both). You can also use a regular expression (indexOf works too, a RegExp is just an option) so:

    var re = new RegExp('*' + word + '*');
    
    if (re.test(div[i].innerText || div[i].textContent)) {
      // div[i] contains /*word*/
    } 
    

    A more robust solution would be like:

    function getText(el) {
      if (typeof el.textContent == 'string') {
        return el.textContent;
      }
      if (typeof el.innerText == 'string') {
        return el.innerText;
      }
    }
    
    var re = new RegExp('*' + word + '*');
    
    if (re.test(getText(div[i]))) {
      // div[i] contains /*word*/
    } 
    

提交回复
热议问题