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

javascript - Determine text inside a DIV is in Bold - Stack Overflow

programmeradmin1浏览0评论

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

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

Share Improve this question asked Apr 30, 2013 at 12:38 ExceptionException 8,38924 gold badges88 silver badges141 bronze badges 3
  • stackoverflow./about – Xotic750 Commented May 11, 2013 at 9:26
  • @Xotic750 Where does that link apply to the current context? – Exception Commented May 14, 2013 at 4:38
  • "Stack Overflow is a question and answer site", there has been no activity in two weeks, did you find a solution? If it was none of those suggested below, then perhaps you could share your answer, and even mark it as the answer you selected to your question. "This site is all about getting answers", quotes are from link above. – Xotic750 Commented May 14, 2013 at 12:47
Add a ment  | 

5 Answers 5

Reset to default 3
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

Perhaps like this, this selects each element on the page and then checks it's puted 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

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 puted = window.getComputedStyle(node, null);

        if(puted && puted.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/bxcTp/1/

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.

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.

发布评论

评论列表(0)

  1. 暂无评论