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

If my html page is having lot of text and some words having formatting. If I use windows.find(text);I

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744370326a4570915.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信