codyLine
codyLine

Reputation: 519

getElementById - Javascript

I'm using the Google autocomplete javascript code for address completion. It tracks the imput field getting the Id document.getElementById('addressField'). The problem I have is that the id of the input field looks like myForm:j_idt329:addressField. I need this in many different pages. So the id looks each time different but always contains the word addressField at the end. Is there another approach how to get the element? Maybe with RegEx? Here is the complete javascript:

function initialize() {

var input = document.getElementById('addressField');
var options = {
    types: ['geocode']
};

var autocomplete = new google.maps.places.Autocomplete(input, options);

}
google.maps.event.addDomListener(window, 'load', initialize);

Thanks in advance.

Upvotes: 2

Views: 166

Answers (1)

Sterling Archer
Sterling Archer

Reputation: 22395

Regex not needed! You can use querySelector

document.querySelector("[id*='addressField']")

If I remember correctly, the *= operator in a selector looks for elements that contain addressField

If you are trying to get a nodelist of multiple of these elements, simply use querySelectorAll instead. The former just returns the first node of the list, all returns the whole list.

As Lucas said in the comments: $= will match the end of the attribute. Both will work, not 100% sure if one is better than the other however.

Upvotes: 5

Related Questions