Exception
Exception

Reputation: 8389

Determine text inside a DIV is in Bold

I have a HTML structure like below

<div>Some text</div>
<div class='inBold'>Hello <b>Dude</b></div>
<div class='inBold'>Hello <span class="boldText">Dude</span></div>
<div class='inBold'>Hello <strong>Dude</strong></div>

and CSS is

.boldText{ font-weight : bold; }

Now I just wanted to check whether a string Dude is in bold of all DIVs. It seems like dealing with HTML would be messy as there are so many ways to give bold formatting. How can I identify whether some text inside a DIV is in bold or not. Please help me on this

Upvotes: 2

Views: 6448

Answers (5)

Xotic750
Xotic750

Reputation: 23492

Perhaps like this, this selects each element on the page and then checks it's computed style for font-weight set as ´bold´ (can also be by ´b´ or ´strong). If it matches this rule then the element is logged to the console.

Note: getComputedStyle detects 'b' and 'strong' and so no extra tests are required to detect those elements.

CSS

.boldText {
    font-weight : bold;
}

HTML

<div>Some text</div>
<div class='inBold'>Hello <b>Dude</b>
</div>
<div class='inBold'>Hello <span class="boldText">Dude</span>
</div>
<div class='inBold'>Hello <strong>Dude</strong>
</div>

Javascript

Array.prototype.forEach.call(document.querySelectorAll("*"), function (element) {
    if (window.getComputedStyle(element).fontWeight === "bold") { // can also use .getPropertyValue("font-weight")
        console.log("bold: ", element);
    }
});

On jsfiddle

Of course this is checking everything on the page but it is fairly simple to look for your required text and check just those elements using this principle.

By changing to this line:

if (element.textContent === "Dude" && window.getComputedStyle(element).fontWeight.toLowerCase() === "bold") {

On jsfiddle

Note: getComputedStyle is not supported on older browsers, and neither is Array.forEach

document.querySelectorAll is also not supported on all older browsers.

There are plenty of shims out these for Array.forEach, or alteratively you can change it to a for or while loop.

getComputedStyle is s little more of a problem, but if you need something that is more cross browser, then this should give you wider support.

Javascript

function walkTheDOM(node, func) {
    func(node);
    node = node.firstChild;
    while (node) {
        walkTheDOM(node, func);
        node = node.nextSibling;
    }
}

function textContent(node) {
    if (typeof node.textContent !== "undefined" && node.textContent !== null) {
        return node.textContent;
    }

    var text = ""

    walkTheDOM(node, function (current) {
        if (current.nodeType === 3) {
            text += current.nodeValue;
        }
    });

    return text;
}

function camelCase(string) {
    return string.replace(/-([a-z])/g, function (matched) {
        return matched[1].toUpperCase()
    });
}

function getComputedStyleProperty(element, property) {
    if (!window.getComputedStyle) {
        if (document.defaultView && document.defaultView.getComputedStyle) {
            return document.defaultView.getComputedStyle(element).getPropertyValue(property);
        } else {
            var camelCased = camelCase(property);

            if (element.currentStyle) {
                return element.currentStyle[camelCased];
            } else {
                return element.style[camelCased];
            }
        }
    } else {
        return window.getComputedStyle(element).getPropertyValue(property);
    }
}

var elements = document.getElementsByTagName("*"),
    length = elements.length,
    i = 0,
    element;

while (i < length) {
    element = elements[i];

    if (textContent(element) === "Dude" && getComputedStyleProperty(element, "font-weight") === "bold") {
        console.log("bold: ", element);
    }

    i += 1;
}

On jsfiddle

Upvotes: 2

Sirko
Sirko

Reputation: 74086

You can use the getComputedStyle() function to determine the current value of an element. This includes any inherited values from parent elements:

// get a pointer to your element somehow
var elem;

// get the current weight
var weight = window.getComputedStyle(elem,null).getPropertyValue("font-weight");

A "mapping" form the numeric values to identifiers like bold can be found in the MDN article on font-weight.

Upvotes: 1

Mircea
Mircea

Reputation: 11623

This will create a treeWalker and check for each node with text content "Dude" for bold propriety regardless of the className or tagName:

var treeWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_ALL, filter, false);

function filter(node) {
    if (node.textContent === 'Dude') {
        var computed = window.getComputedStyle(node, null);

        if(computed && computed.getPropertyValue("font-weight")=== "bold"){
            return NodeFilter.FILTER_ACCEPT;
        }

    } else {
        return NodeFilter.FILTER_SKIP;
    }
}

while(treeWalker.nextNode()) {
    //    Elements with bold text
    console.log(treeWalker.currentNode)
};

http://jsfiddle.net/bxcTp/1/

Upvotes: 2

karaxuna
karaxuna

Reputation: 26940

var divs = document.getElementsByClassName('inBold');
for(var i = 0; i < divs.length; i++)
    console.log(isBold(divs[i]));

function isBold(node){
     var childNodes = node.childNodes;
     for(var i = 0; i < childNodes.length; i++)
         if(childNodes[i].nodeType != 3 && (childNodes[i].className.indexOf('boldText') != -1 
            || childNodes[i].tagName == 'B'
            || childNodes[i].tagName == 'STRONG'))
             return true;
     return false;
}

See fiddle

Upvotes: 3

Marek Lewandowski
Marek Lewandowski

Reputation: 3401

If you can use jQuery you can use this sample:

var consideredBoldsSelector = 'b, strong, span.boldText';
var expectedCount = $("div.inBold").length
var bAllMatched = $("div.inBold *:contains('Dude'):first-child").filter(consideredBoldsSelector).length === expectedCount

With expectedCount you can manipulate how many "hits" you're expecting, and with consideredBoldsSelector you can easily add css-alike selectors for your bolds.

Note that :contains is case-sensitive.

Upvotes: 0

Related Questions