0

Looking access the label text.

I can find the value of the input tag via:

<label for="t">Try this <input type="text" id="t" /></label>
<input type="button" onclick="alert(document.getElementById('t').value)" value="Click me!"/>

But what is the method to access the label's text "Try this" ?

using .innerHTML yields nothing. .parentNode.value yielded undefined.

3 Answers 3

3

<label for="t">Try this <input type="text" id="t" /></label>
<input type="button" onclick="alert(document.getElementById('t').parentNode.innerText)" value="Click me!"/>

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. .parentNode.innerText -- didn't want to have to have to add an id to the label in addition to a for property. Seemed redundant.
0

You can search the element by their tag name using document.getElementsTagName() method. This method returns all elements with the tag <label></label>

<label for="t">Try this <input type="text" id="t" /></label>
<input type="button" onclick="alert(document.getElementsByTagName('label')[0].innerText)" value="Click me!"/>

11 Comments

why [0]? [1]? [2]?
because document.getElementsTagName() retrieves all existing element with the given tag name, therefore, it obviously returns array even if there is only one element
I know this but why [0]?
You really don't know? we need index to retrieve element from array.don't we?
Where are you going with this?
|
0

Give your label an id, let's say lbl:

<label id="lbl" for="t">Try this <input type="text" id="t" /></label>

Now in javascript, you can access the text using:

document.getElementById('lbl').innerText

you can also trim the result to get rid of spaces.

8 Comments

That does not work. It returns Try this <input type="text" id="t">.
.innerHTML returns Try this <input type="text" id="t">.
as you can see in the answer, use innerText not innerHTML
.innerText will return "Try this" which is what I am looking for but each label has to also have a id to match the input tag id. the for property doesn't seem to do anything.
This is depending on your HTML structure which is not mentioned in your question. furthermore, if your inputs are always nested within the label, you can use the inputelement.parentNode() . On the other hand, the for property tells the label which input to focus when clicked
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.