最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Javascript: $('body:contains("")') with html - Stack Overflow

programmeradmin0浏览0评论

I want to use $('body:contains("")') for searching part of a html code.

For example:

var thing = $('body:contains("Web</a></td></tr>")').text()
    if(thing) {
        alert(thing);
    }
else{
    alert("not found")
        }

This code always alerts "not found".

Is it possible to search a part of a html code and alert if found?

Thank you...

I want to use $('body:contains("")') for searching part of a html code.

For example:

var thing = $('body:contains("Web</a></td></tr>")').text()
    if(thing) {
        alert(thing);
    }
else{
    alert("not found")
        }

This code always alerts "not found".

Is it possible to search a part of a html code and alert if found?

Thank you...

Share Improve this question edited Jul 17, 2011 at 10:05 Brock Adams 93.7k23 gold badges241 silver badges305 bronze badges asked Jul 16, 2011 at 23:31 Ahmet Can GüvenAhmet Can Güven 5,4624 gold badges42 silver badges61 bronze badges 1
  • 1 Beware that you may see "Web</a></td></tr>", when inspecting with your browser, but the actual code may contain whitespace or not even have closing tags! Even if the source is "Web</a></td></tr>" now, stuff like that can break very easily on pages that you do not control. – Brock Adams Commented Jul 17, 2011 at 0:11
Add a ment  | 

3 Answers 3

Reset to default 6

You can't use selectors to look for HTML fragments, as no element contains the HTML fragment as text.

You can put the elements in the selector as elements, and look only for the text part of your HTML fragement:

var thing = $('body tr > td > a:contains("Web")').text();

:contains() searches text, not markup. To find an element whose HTML contents (innerHTML) includes a given string, you can use .filter() like:

$('body').filter(function() {
    return this.innerHTML.indexOf('Web</a></td></tr>') > -1;
});

:contains doesn't check html. You could instead do:

if (document.body.innerHTML.indexOf('Web</a></td></tr>') > -1) {
    // whatever
}
发布评论

评论列表(0)

  1. 暂无评论