Skip to content Skip to sidebar Skip to footer

How To Check Whether A Text Is Having Bold In A Web Page

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 te

Solution 1:

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.net/efN8P/

Code:

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

Solution 2:

This works but I'm not sure about cross-browser compatibility: http://jsfiddle.net/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);

Post a Comment for "How To Check Whether A Text Is Having Bold In A Web Page"