[javascript] How to get label text value form a html page?

I have a html page , where the html is rendered as :

<div id = 'mViB'>
<table id = 'myTable'>
<tbody>
<tr> ...</tr>
<tr>...</tr>
<tr> ...</tr>
<tr>....</tr>
<tr>
<td>
<label id="*spaM4" for="*zigField4">
All hell.
<span class = 'msde32'></span>
</label>
</td>
</tr>
</tbody>
</table>
</div>

Now what i want to do is get the label text 'All hell.' from the label.

For that purpose i have used both : document.getElementById('*spaM4').text and document.getElementById('*spaM4').value but incidentally none of them worked.

I have used document.getElementById('*spaM4').innerHTML but that returns the span class as well, but i just want to get the text .

Unfortunately, the asterisks in element IDs are 3rd party code and I cannot change it.

Can any one suggest any other way for getting the label text ?

This question is related to javascript

The answer is


var lbltext = document.getElementById('*spaM4').innerHTML

You can use textContent attribute to retrieve data from a label.

 <script>
       var datas = document.getElementById("excel-data-div").textContent;
    </script>


<label id="excel-data-div" style="display: none;">
     Sample text
</label>

The best way to get the text value from a <label> element is as follows.

if you will be getting element ids frequently it's best to have a function to return the ids:

function id(e){return document.getElementById(e)}

Assume the following structure: <label for='phone'>Phone number</label> <input type='text' id='phone' placeholder='Mobile or landline numbers...'>

This code will extract the text value 'Phone number' from the<label>: var text = id('phone').previousElementSibling.innerHTML;

This code works on all browsers, and you don't have to give each<label>element a unique id.


Use innerText/textContent:

  var el = document.getElementById('*spaM4');
  console.log(el.innerText || el.textContent);

Fiddle: http://jsfiddle.net/NeTgC/2/


For cases where the data element is inside the label like in this example:

<label for="subscription">Subscription period
    <select id='subscription' name='subscription'>
        <option></option>
        <option>1 year</option>
        <option>2 years</option>
        <option>3 years</option>
    </select>
</label>

all the previous answers will give an unexpected result:

"Subscription period


                    1 year
                    2 years
                    3 years

            "

While the expected result would be:

"Subscription period"

So, the correct solution will be like this:

const label = document.getElementById('yourLableId');
const labelText = Array.prototype.filter
    .call(label.childNodes, x => x.nodeName === "#text")
    .map(x => x.textContent)
    .join(" ")
    .trim();

This will get what you want in plain JS.

var el = document.getElementById('*spaM4');
text = (el.innerText || el.textContent);

FIDDLE