Javascript - check if div contains a word?

北慕城南 提交于 2019-12-31 11:36:12

问题


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) {

    if (divs[i].text = '*word*'){
    //do somthing
}
}

doesn't work.


回答1:


use the indexOf function

if(divs[i].innerHTML.indexOf("word") !== -1) {
    // something
}



回答2:


Use includes():

node.textContent.includes('Some text');



回答3:


if (document.getElementById('divId').innerHTML.indexOf("word") != -1) { }



回答4:


Try the String.indexOf() function: if (divs[i].text.indexOf('word') != -1) {




回答5:


You have to use a comparison operator not assign a variable.

if (divs[i].text == '*word*'){

I would recommend to use indexOf.

if (divs[i].text.indexOf('*word*') != -1){



回答6:


In addition to what others said about using .indexOf() function, I'd like to say .text is not a div node property. User .innerHTML

if (divs[i].innerHTML.indexOf('word') > -1){}



回答7:


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*/
} 



回答8:


use regexp:

if ( divs[i].textContent.match ( /\bword\b/ ) ){
    //do something
}

@RobG remind me so

if ( divs[i].innerHTML.match ( /\bword\b/ ) ){
    //do something
}

=3=



来源:https://stackoverflow.com/questions/9627289/javascript-check-if-div-contains-a-word

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!