/    Sign up×
Community /Pin to ProfileBookmark

Use Javascript to overwrite label for input?

`<div id=”form”>`

`<div class=”field”>`
`<label for=”fname”>`
`<span class=”label”>First</span>`
`</label>`
`<div class=”fnameinput”><input type=”text” name=”name” id=”fname”></div>`
`</div>`

`<div class=”field”>`
`<label for=”lname”>`
`<span class=”label”>Last</span>`
`</label>`
`<div class=”lnameinput”><input type=”text” name=”name” id=”lname”></div>`
`</div>`

`</div>`

In this situation, where there isn’t a unique identifier for the label text, is there anyway to overwrite/update it with javascript?

e.g. change `<span class=”label”>First</span>` from First to First Name

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@NachfolgerNov 02.2020 — If you control the HTML, I strongly encourage you to add a unique identifier to the element.

Regardless, yes--It is possible.

``JavaScript<i>
</i>document.querySelector("#form .field label[for='fname']");<i>
</i>
`</CODE>
Didn't fact check it, but it should work. The <C>
querySelector` function is basically the same thing as a CSS element selector.
Copy linkTweet thisAlerts:
@nickdclementsauthorNov 02.2020 — document.getElementsByTagName("label")[0].innerHTML = "First Name";
Copy linkTweet thisAlerts:
@NachfolgerNov 02.2020 — > @nickdclements#1624801 document.getElementsByTagName("label")[0].innerHTML = "First Name";

That also works. By the way, you're not editing the HTML--You're editing the text. I would suggest using .textContent or .innerText.
×

Success!

Help @nickdclements spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.25,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...