如何使用 JavaScript 更改 <label for> 值?

How do I change the <label for> value, using JavaScript?

我有一个带有标签的简单 HTML 文本框,我希望能够使用 JavaScript 更改标签值。我已经尝试了下面概述的各种方法,但似乎都没有成功。如有任何帮助,我们将不胜感激!

HTML:

<html>
    <body>
    
    <li id="job_number_wrapper">
        <label for="job_number">I WANT TO CHANGE THIS TEXT</label>
        <input type="text" id="job_number" name="job_number">
    </li>

Javascript:

<script>

function myFunction() {
    document.getElementById("job_number").htmlForVal = "New text"; //does nothing
    
    if (job_number_wrapper.textContent)
        job_number_wrapper.textContent = "New Text";  //changes text, but removes text box
    
    if (job_number.textContent)
        job_number.textContent = "New Text";  //does nothing
        
        
    $("label[for=job_number]").html("New Text"); //does nothing
    $("label[for=job_number]").text("New Text"); //does nothing
    
    document.getElementById('job_number').innerHTML = 'New Text'; //does nothing
    document.getElementById('job_number').innerText = 'New Text'; //does nothing
    document.getElementById('job_number').value = 'New Text'; //does nothing
    
    $('#job_number').val("New Text"); //populates the textbox value, but does not change the label
    
    
    var label = document.querySelector('label[for="job_number"]');  //does nothing
    label.textContent = "New Text"        //does nothing
}
    
myFunction();
    
</script>
</body>
</html>

你错过了里面的'

$("label[for='job_number]'").html("New Text"); 
$("label[for='job_number]'").text("New Text"); 

您没有 select 使用 document.getElementById("job_number") 标签。相反,试试这个:

const labelEl = document.querySelector('#job_number_wrapper label');

或者,您可以为您的标签提供 ID 或 class,然后直接 select。

当您尝试调用 querySelector 时,您几乎做对了:

var label = document.querySelector('label[for="job_number"]');  //does nothing
label.textContent = "New Text"        //does nothing

此 select 或失败的唯一原因是您对 select 和 job_number 使用了双引号。删除它们,它将起作用:

var label = document.querySelector("label[for=job_number]");
label.textContent = "New Text";
<label for="job_number">I WANT TO CHANGE THIS TEXT</label>
<input type="text" id="job_number" name="job_number" />

另请参阅:related question

 function test() {
        const e = document.querySelector("label[for=job_number]");
        e.innerText = "some other name";
        
      }
 <li id="job_number_wrapper">
        <label for="job_number">I WANT TO CHANGE THIS TEXT</label>
        <input type="text" id="job_number" name="job_number" />
      </li>
      
<button onclick="test()">change label text</button>

你可以简单地使用这个逻辑来玩转标签