2

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.

1 Answer 1

5

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.

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

4 Comments

Better yet, $= will match only if the attribute ends with the given string.
@LucasTrzesniewski there's that too yes! I wonder if there is a speed difference?
Sure, you'll get a microsecond improvement :)
That's a whole microsecond I didn't have before!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.