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

javascript - How to check whether a text is having bold in a web page - Stack Overflow

programmeradmin9浏览0评论

If my html page is having lot of text and some words having formatting. If I use

windows.find(text);

It will help to find text in a web page. But how can I know the searched text is in bold in the document?

For example if my page HTML is:

 <body>
      Hello Techie, <b>I</b> am in bold.
 </body>

If I use window.find("I am") it will match the text. But how can I know that whether "I am" is in bold or not?

I hope question is clear. Please let me know if you want any further input to be helpful.

If my html page is having lot of text and some words having formatting. If I use

windows.find(text);

It will help to find text in a web page. But how can I know the searched text is in bold in the document?

For example if my page HTML is:

 <body>
      Hello Techie, <b>I</b> am in bold.
 </body>

If I use window.find("I am") it will match the text. But how can I know that whether "I am" is in bold or not?

I hope question is clear. Please let me know if you want any further input to be helpful.

Share Improve this question edited Jul 14, 2015 at 9:50 BoltClock 725k165 gold badges1.4k silver badges1.4k bronze badges asked Feb 25, 2012 at 15:51 ExceptionException 8,38924 gold badges88 silver badges141 bronze badges 1
  • i guess regex expressions most be involved. – Ofir Baruch Commented Feb 25, 2012 at 15:55
Add a ment  | 

2 Answers 2

Reset to default 4

window.find(), where supported, moves the selection to the text it has found. This being the case, you can use document.queryCommandState() to check the boldness of the selected content, which has the advantage of working regardless of how the boldness is set (CSS font-weight, <b> or <strong> elements). Unfortunately in non-IE browsers you have to temporarily put the document into design mode to make this work:

Demo: http://jsfiddle/efN8P/

Code:

document.designMode = "on";
window.find("I am");
var isAllBold = document.queryCommandState("Bold");
alert(isAllBold);
document.designMode = "off";

This works but I'm not sure about cross-browser patibility: http://jsfiddle/VALr3/1/. It checks whether a <b> element is part of the selected elements.

window.find("I am");

var sel = window.getSelection(),
    frag = sel.rangeCount > 0 && sel.getRangeAt(0).cloneContents();

alert(frag && frag.querySelectorAll("b").length > 0);
发布评论

评论列表(0)

  1. 暂无评论