简体   繁体   中英

How to change the text of a “label for” using javascript/jquery?

<label for="id_about">Profile</label>

How do I change this using JavaScript or jQuery? I want to only change this instance to replace profile with something else like About. I know how to change all "Profile" word from my website. But I only want to change this particular specific instance.

You can search using attributes:

$("label[for=id_about]").html("new text here"); // or .text("new text here")

Remember that jQuery lets you use the full power of CSS selectors to find elements on the page (it even adds some of its own, but in general try to stick to official ones).


For anyone who doesn't use jQuery, you can still use the full range of CSS selectors on any modern browser (and IE8) via querySelector (find the first matching element, or null if no match) or querySelectorAll (get a NodeList of matching elements, which might be empty):

document.querySelector("label[for=id_about]").innerHTML = "new text here";

This is the solution without JQuery, working with any browser. Supposing this is part of your HTML:

<label id="myLabel" for="myTextField">my label text</label>
<input type="text" id="myTextField"/>
<input type="submit" id="byBtn" value="Change" onclick="change()"/>

This is the change() function to alter the label content:

function change(){
    var labelText = document.getElementById('myLabel');
    labelText.innerHTML = "new label text";
}

Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM