Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: get custom button's text value

I have a button that is defined as follows :

<button type="button" id="ext-gen26" class=" x-btn-text">button text here</button> 

And I'm trying to grab it based on the text value. Hhowever, none of its attributes contain the text value. It's generated in a pretty custom way by the look of it.

Does anyone know of a way to find this value programmatically, besides just going through the HTML text? Other than attributes?

Forgot one other thing, the id for this button changes regularly and using jQuery to grab it results in breaking the page for some reason. If you need any background on why I need this, let me know.

This is the JavaScript I am trying to grab it with:

var all = document.getElementsByTagName('*');  for (var i=0, max=all.length; i < max; i++)  { var elem = all[i]; if(elem.getAttribute("id") == 'ext-gen26'){     if(elem.attributes != null){         for (var x = 0; x < elem.attributes.length; x++) {             var attrib = elem.attributes[x];             alert(attrib.name + " = " + attrib.value);           }     } } }; 

It only comes back with the three attributes that are defined in the code.

innerHTML, text, and textContent - all come back as null.

like image 794
hacket Avatar asked Apr 27 '12 13:04

hacket


People also ask

Can I get value from Button JavaScript?

Use the value property to get the value of a button in JavaScript.

How do you name a button in JavaScript?

The name property sets or returns the value of the name attribute of a button. The name attribute specifies the name of a button, and is used to reference form data after it has been submitted, or to reference the element in a JavaScript.


1 Answers

You can do that through the textContent/innerText properties (browser-dependant). Here's an example that will work no matter which property the browser uses:

var elem = document.getElementById('ext-gen26'); var txt = elem.textContent || elem.innerText; alert(txt); 

http://jsfiddle.net/ThiefMaster/EcMRT/

You could also do it using jQuery:

alert($('#ext-gen26').text()); 
like image 154
ThiefMaster Avatar answered Oct 09 '22 05:10

ThiefMaster