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

javascript - find the label's for attribute value that has the following text - Stack Overflow

programmeradmin3浏览0评论

I have the below HTML Code and need to get the label's for attribute value where text = 'Complaint'; I couldn't find a proper way to get this done and this because the items inside the span are loading dynamically. Therefore I cant just get the value with the generated id hence I need to find the ID using the label. If that label exist i.e. <label for="CSSMLCall_call_oute_types_1">Complaint</label>. I need to get its for attr val.

Is this a possible thing to do with Jquery?

<span id="CSSMLCall_call_oute_types">
<input type="checkbox" name="CSSMLCall[call_oute_types][]" value="5238" class="session_oute_chk_list" id="CSSMLCall_call_oute_types_0"> 
<label for="CSSMLCall_call_oute_types_0">Client didn’t engage</label>
<input type="checkbox" name="CSSMLCall[call_oute_types][]" value="4287" class="session_oute_chk_list" id="CSSMLCall_call_oute_types_1"> 
<label for="CSSMLCall_call_oute_types_1">Complaint</label>

</span>

Instead of $("#CSSMLCall_call_oute_types_4").is(":checked"), i need to find the id using the label and then do the same.

Any prompt reply is highlight appreciable.

I have the below HTML Code and need to get the label's for attribute value where text = 'Complaint'; I couldn't find a proper way to get this done and this because the items inside the span are loading dynamically. Therefore I cant just get the value with the generated id hence I need to find the ID using the label. If that label exist i.e. <label for="CSSMLCall_call_oute_types_1">Complaint</label>. I need to get its for attr val.

Is this a possible thing to do with Jquery?

<span id="CSSMLCall_call_oute_types">
<input type="checkbox" name="CSSMLCall[call_oute_types][]" value="5238" class="session_oute_chk_list" id="CSSMLCall_call_oute_types_0"> 
<label for="CSSMLCall_call_oute_types_0">Client didn’t engage</label>
<input type="checkbox" name="CSSMLCall[call_oute_types][]" value="4287" class="session_oute_chk_list" id="CSSMLCall_call_oute_types_1"> 
<label for="CSSMLCall_call_oute_types_1">Complaint</label>

</span>

Instead of $("#CSSMLCall_call_oute_types_4").is(":checked"), i need to find the id using the label and then do the same.

Any prompt reply is highlight appreciable.

Share Improve this question edited Jun 18, 2013 at 10:47 Sanjeev Rai 7,0124 gold badges24 silver badges33 bronze badges asked Jun 18, 2013 at 10:42 dev1234dev1234 5,72616 gold badges61 silver badges118 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 2

I'd suggest:

var id = $('label').filter(function(){
             return $(this).text().trim() == 'Complaint';
         }).attr('for');

References:

  • attr().
  • filter().
  • text().
var id = $('label:contains("Complaint")').attr('for');

For anyone looking for an answer with Javascript only use htmlFor:

var id = label.htmlFor;

Like:

var id = document.getElementById("myLabel").htmlFor;

try

var id = $('label[for]').filter(function(){
    return $.trim($(this).text()) == 'Complaint'
}).attr('for')

Here is an alternative to using jquery written in POJS.

HTML

<span id="CSSMLCall_call_oute_types">
<input type="checkbox" name="CSSMLCall[call_oute_types][]" value="5238" class="session_oute_chk_list" id="CSSMLCall_call_oute_types_0"> 
<label for="CSSMLCall_call_oute_types_0">Client didn’t engage</label>
<input type="checkbox" name="CSSMLCall[call_oute_types][]" value="4287" class="session_oute_chk_list" id="CSSMLCall_call_oute_types_1"> 
<label for="CSSMLCall_call_oute_types_1">Complaint</label>
</span>

Javascript

/*jslint maxerr: 50, indent: 4, browser: true */
/*global console, jQuery, $ */

(function () {
    "use strict";

    function walkTheDOM(node, func) {
        if (node && node.nodeType) {
            if (typeof func === "function") {
                func(node);
            }

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

    function escapeRegex(string) {
        return string.replace(/[\[\](){}?*+\^$\\.|]/g, "\\$&");
    }

    function filterElementsByContains(elements, string) {
        var toStringFN = {}.toString,
            text = toStringFN.call(elements),
            result,
            length,
            i,
            element;

        if (text !== "[object NodeList]" && text !== "[object Array]" && !($() instanceof jQuery)) {
            return result;
        }

        result = [];
        if (typeof string === "string") {
            string = new RegExp("^" + escapeRegex(string) + "$");
        } else if (toStringFN.call(string) !== "[object RegExp]") {
            return result;
        }

        function getText(node) {
            if (node.nodeType === 3) {
                text += node.nodeValue;
            }
        }

        length = elements.length;
        i = 0;
        while (i < length) {
            text = "";
            element = elements[i];
            walkTheDOM(element, getText);
            if (string.test(text)) {
                result.push(element);
            }

            i += 1;
        }

        return result;
    }

    function getAttribute(node, attribute) {
        var undef;

        if (!node || !node.nodeType || !attribute || typeof attribute !== "string" || !node.attributes || node.attributes[attribute] === undef) {
            return undef;
        }

        return node.attributes[attribute].nodeValue;
    }

    var labels = document.getElementsByTagName("label");

    console.log(getAttribute(filterElementsByContains(labels, "Complaint")[0], "for"));
    console.log(filterElementsByContains(labels, "C"));
    console.log(filterElementsByContains(labels, /C/));
    console.log(filterElementsByContains(labels, /client/i));
    console.log(filterElementsByContains(labels, "Client"));
    console.log(filterElementsByContains($("label"), /Client/));
}());

Output

CSSMLCall_call_oute_types_1
[]
[label, label]
[label]
[]
[label]

On jsfiddle

With these functions, you can supply a NodeList, an Array of Elements, or a jQuery object as the elements parameter. The string parameter can be either a string or a regex.

It will return an Array of filtered elements that either contain an exact match for the supplied string, or for the matched regex.

I believe this is more powerful/flexible than the jquery :contains selector which can only filter by whether the text is contained directly within the selected element.

These functions should be cross-broswer friendly, although I can't test every browser out there, or every possible condition.

I have also create a jsperf so that you can pare the jquery method vs this answer.

Anyway, I thought I'd share this alternative with you, and someone else may also find it useful.

发布评论

评论列表(0)

  1. 暂无评论