code

주어진 입력과 관련된 html 레이블 찾기

codestyles 2020. 8. 21. 07:48
반응형

주어진 입력과 관련된 html 레이블 찾기


html 양식이 있다고 가정 해 봅시다. 각 입력 / 선택 / 텍스트 영역은 해당해야합니다 <label>for그것의 동반자의 id에 속성 세트를. 이 경우 각 입력에는 하나의 레이블 만 있음을 알고 있습니다.

예를 들어 onkeyup 이벤트를 통해 자바 스크립트의 입력 요소가 주어지면 관련 레이블을 찾는 가장 좋은 방법은 무엇입니까?


먼저 페이지에서 레이블을 스캔하고 실제 양식 요소에서 레이블에 대한 참조를 할당합니다.

var labels = document.getElementsByTagName('LABEL');
for (var i = 0; i < labels.length; i++) {
    if (labels[i].htmlFor != '') {
         var elem = document.getElementById(labels[i].htmlFor);
         if (elem)
            elem.label = labels[i];         
    }
}

그런 다음 간단하게 이동할 수 있습니다.

document.getElementById('MyFormElem').label.innerHTML = 'Look ma this works!';

조회 배열이 필요하지 않습니다. :)


jQuery를 사용하는 경우 다음과 같이 할 수 있습니다.

$('label[for="foo"]').hide ();

jQuery를 사용하지 않는 경우 레이블을 검색해야합니다. 다음은 요소를 인수로 사용하고 관련 레이블을 반환하는 함수입니다.

function findLableForControl(el) {
   var idVal = el.id;
   labels = document.getElementsByTagName('label');
   for( var i = 0; i < labels.length; i++ ) {
      if (labels[i].htmlFor == idVal)
           return labels[i];
   }
}

HTML5 표준 에는 입력 요소와 관련된 레이블을 가리키는 labels속성 이 있습니다 .

따라서 다음과 같은 것을 사용할 수 있습니다 (기본 labels속성을 지원 하지만 브라우저가 지원하지 않는 경우 레이블 검색을위한 대체 기능 포함) ...

var getLabelsForInputElement = function(element) {
    var labels = [];
    var id = element.id;

    if (element.labels) {
        return element.labels;
    }

    id && Array.prototype.push
        .apply(labels, document.querySelector("label[for='" + id + "']"));

    while (element = element.parentNode) {
        if (element.tagName.toLowerCase() == "label") {
            labels.push(element);
        }  
    }

    return labels;
};

// ES6
var getLabelsForInputElement = (element) => {
    let labels;
    let id = element.id;

    if (element.labels) {
        return element.labels;
    }

    if (id) {
        labels = Array.from(document.querySelector(`label[for='${id}']`)));
    }

    while (element = element.parentNode) {
        if (element.tagName.toLowerCase() == "label") {
            labels.push(element);
        }  
    }

    return labels;
};

jQuery를 사용하는 경우 더 쉽습니다.

var getLabelsForInputElement = function(element) {
    var labels = $();
    var id = element.id;

    if (element.labels) {
        return element.labels;
    }

    id && (labels = $("label[for='" + id  + "']")));

    labels = labels.add($(element).parents("label"));

    return labels;
};

나는 당신이 완벽하게 할 수 있다는 것을 아무도 모른다는 것에 약간 놀랐습니다 .

<label>Put your stuff here: <input value="Stuff"></label>

어떤 제안 된 답변 중 하나에 의해 선택되지 않습니다,하지만 것입니다 올바르게 입력 레이블을 붙입니다.

이 경우를 고려하는 몇 가지 코드는 다음과 같습니다.

$.fn.getLabels = function() {
    return this.map(function() {
        var labels = $(this).parents('label');
        if (this.id) {
            labels.add('label[for="' + this.id + '"]');
        }
        return labels.get();
    });
};

용법:

$('#myfancyinput').getLabels();

몇 가지 참고 사항 :

  • 코드는 성능이 아닌 명확성을 위해 작성되었습니다. 더 성능이 좋은 대안을 사용할 수 있습니다.
  • 이 코드는 한 번에 여러 항목의 레이블을 가져 오는 것을 지원합니다. 그것이 당신이 원하는 것이 아니라면 필요에 따라 적응하십시오.
  • 이것은 aria-labelledby당신이 그것을 사용하는 것과 같은 것들을 여전히 처리하지 않습니다 (독자에게 연습으로 남겼습니다).
  • 여러 레이블을 사용하는 것은 서로 다른 사용자 에이전트 및 보조 기술을 지원할 때 까다로운 비즈니스이므로 잘 테스트하고 자신의 위험을 감수하고 사용하십시오.
  • 예, jQuery를 사용하지 않고이를 구현할 수도 있습니다. :-)

일찍이...

var labels = document.getElementsByTagName("LABEL"),
    lookup = {},
    i, label;

for (i = 0; i < labels.length; i++) {
    label = labels[i];
    if (document.getElementById(label.htmlFor)) {
        lookup[label.htmlFor] = label;
    }
}

나중...

var myLabel = lookup[myInput.id];

Snarky comment : 예, JQuery로도 할 수 있습니다. :-)


document.querySelector ( "label [for ="+ vHtmlInputElement.id + "]");

이것은 가장 간단하고 간결한 방식으로 질문에 답합니다. 이것은 바닐라 자바 ​​스크립트를 사용하고 모든 메인 스트림 적절한 브라우저에서 작동합니다.


jquery를 사용하면 다음과 같이 할 수 있습니다.

var nameOfLabel = someInput.attr('id');
var label = $("label[for='" + nameOfLabel + "']");

querySelector를 기꺼이 사용하려는 경우 (IE9 및 때로는 IE8까지도 가능합니다!) 다른 방법 을 사용할 수 있습니다.

양식 필드에 ID가 있고 레이블의 for속성 을 사용하는 경우 최신 JavaScript에서는이 작업이 매우 간단 해집니다.

var form = document.querySelector('.sample-form');
var formFields = form.querySelectorAll('.form-field');

[].forEach.call(formFields, function (formField) {
    var inputId = formField.id;
    var label = form.querySelector('label[for=' + inputId + ']');
    console.log(label.textContent);
});

일부는 여러 레이블에 대해 언급했습니다. 모두 for속성에 대해 동일한 값을 사용 querySelectorAll하는 경우 대신에 사용 querySelector하고 필요한 모든 항목을 반복합니다.


$("label[for='inputId']").text()

이것은 ID를 사용하여 입력 요소의 레이블을 얻는 데 도움이되었습니다.


Gijs의 답변은 저에게 가장 귀중했지만 안타깝게도 확장 기능이 작동하지 않습니다.

다음은 작동하는 다시 작성된 확장입니다. 누군가에게 도움이 될 수 있습니다.

jQuery.fn.getLabels = function () {
    return this.map(function () {
        var parentLabels = $(this).parents('label').get();
        var associatedLabels = this.id ? associatedLabels = $("label[for='" + this.id + "']").get() : [];
        return parentLabels.concat(associatedLabels);
    });
};

실제로 양식 자체의 레이블에 ID를 추가하는 것이 훨씬 쉽습니다. 예를 들면 다음과 같습니다.

<label for="firstName" id="firstNameLabel">FirstName:</label>

<input type="text" id="firstName" name="firstName" class="input_Field" 
       pattern="^[a-zA-Z\s\-]{2,25}$" maxlength="25"
       title="Alphabetic, Space, Dash Only, 2-25 Characters Long" 
       autocomplete="on" required
/>

그런 다음 다음과 같이 간단히 사용할 수 있습니다.

if (myvariableforpagelang == 'es') {
   // set field label to spanish
   document.getElementById("firstNameLabel").innerHTML = "Primer Nombre:";
   // set field tooltip (title to spanish
   document.getElementById("firstName").title = "Alfabética, espacio, guión Sólo, 2-25 caracteres de longitud";
}

The javascript does have to be in a body onload function to work.

Just a thought, works beautifully for me.


As it has been already mentionned, the (currently) top-rated answer does not take into account the possibility to embed an input inside a label.

Since nobody has posted a JQuery-free answer, here is mine :

var labels = form.getElementsByTagName ('label');
var input_label = {};
for (var i = 0 ; i != labels.length ; i++)
{
    var label = labels[i];
    var input = label.htmlFor
              ? document.getElementById(label.htmlFor)
              : label.getElementsByTagName('input')[0];
    input_label[input.outerHTML] = 
        (label.innerText || label.textContent); // innerText for IE8-
}

In this example, for the sake of simplicity, the lookup table is directly indexed by the input HTML elements. This is hardly efficient and you can adapt it however you like.

You can use a form as base element, or the whole document if you want to get labels for multiple forms at once.

No checks are made for incorrect HTML (multiple or missing inputs inside labels, missing input with corresponding htmlFor id, etc), but feel free to add them.

You might want to trim the label texts, since trailing spaces are often present when the input is embedded in the label.


All the other answers are extremely outdated!!

All you have to do is:

input.labels

HTML5 has been supported by all of the major browsers for many years already. There is absolutely no reason that you should have to make this from scratch on your own or polyfill it! Literally just use input.labels and it solves all of your problems.


A really concise solution using ES6 features like destructuring and implicit returns to turn it into a handy one liner would be:

const getLabels = ({ labels, id }) => labels || document.querySelectorAll(`label[for=${id}]`)

Or to simply get one label, not a NodeList:

const getFirstLabel = ({ labels, id }) => labels && labels[0] || document.querySelector(`label[for=${id}]`)

have you tried using document.getElementbyID('id') where id is the id of the label or is the situation that you dont know which one you are looking for


Use a JQuery selector:

$("label[for="+inputElement.id+"]")

For future searchers... The following is a jQuery-ified version of FlySwat's accepted answer:

var labels = $("label");
for (var i = 0; i < labels.length; i++) {
    var fieldId = labels[i].htmlFor;
    if (fieldId != "") {
        var elem = $("#" + fieldId);
        if (elem.length != 0) {
            elem.data("label", $(labels[i]));   
        }
    }
}

Using:

$("#myFormElemId").data("label").css("border","3px solid red");

I know this is old, but I had trouble with some solutions and pieced this together. I have tested this on Windows (Chrome, Firefox and MSIE) and OS X (Chrome and Safari) and believe this is the simplest solution. It works with these three style of attaching a label.

<label><input type="checkbox" class="c123" id="cb1" name="item1">item1</label>

<input type="checkbox" class="c123" id="cb2" name="item2">item2</input>

<input type="checkbox" class="c123" id="cb3" name="item3"><label for="cb3">item3</label>

Using jQuery:

$(".c123").click(function() {
    $cb = $(this);
    $lb = $(this).parent();
    alert( $cb.attr('id') + ' = ' + $lb.text() );
});

My JSFiddle: http://jsfiddle.net/pnosko/6PQCw/


I have made for my own need, can be useful for somebody: JSFIDDLE

$("input").each(function () {
    if ($.trim($(this).prev('label').text()) != "") {
        console.log("\nprev>children:");
        console.log($.trim($(this).prev('label').text()));
    } else {
        if ($.trim($(this).parent('label').text()) != "") {
            console.log("\nparent>children:");
            console.log($.trim($(this).parent('label').text()));
        } else {
            if ($.trim($(this).parent().prev('label').text()) != "") {
                console.log("\nparent>prev>children:");
                console.log($.trim($(this).parent().prev('label').text()));
            } else {
                console.log("NOTFOUND! So set your own condition now");
            }
        }
    }
});

I am bit surprised no one is suggesting to use the CSS relationship method?

in a style sheet you can reference a label from the element selector:

<style>

//for input element with class 'YYY'
input.YYY + label {}

</style>

if the checkbox has an id of 'XXX' then the label would be found through jQuery by:

$('#XXX + label');

You can also apply .find('+ label') to return the label from a jQuery checkbox element, ie useful when looping:

$('input[type=checkbox]').each( function(){
   $(this).find('+ label');
});

The best answer works perfectly fine but in most cases, it is overkill and inefficient to loop through all the label elements.

Here is an efficent function to get the label that goes with the input element:

function getLabelForInput(id)
{
    var el = document.getElementById(id);
    if (!el)
        return null;
    var elPrev = el.previousElementSibling;
    var elNext = el.nextElementSibling;
    while (elPrev || elNext)
    {
        if (elPrev)
        {
            if (elPrev.htmlFor === id)
                return elPrev;
            elPrev = elPrev.previousElementSibling;
        }
        if (elNext)
        {
            if (elNext.htmlFor === id)
                return elNext;
            elNext = elNext.nextElementSibling;
        }
    }
    return null;
}

For me, this one line of code was sufficient:

el = document.getElementById(id).previousElementSibling;

In most cases, the label will be very close or next to the input, which means the loop in the above function only needs to iterate a very small number of times.

참고URL : https://stackoverflow.com/questions/285522/find-html-label-associated-with-a-given-input

반응형