Search code examples
javascripthtml

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.


Solution

  • If you're trying to locate the button entirely by its text content, I'd grab a list of all buttons and loop through them to find this one:

    function findButtonbyTextContent(text) {
      var buttons = document.querySelectorAll('button');
      for (var i=0, l=buttons.length; i<l; i++) {
        if (buttons[i].firstChild.nodeValue == text)
          return buttons[i];
      }  
    }
    

    Of course, if the content of this button changes even a little your code will need to be updated.