You want to use document.querySelector()
, which, unlike document.getElementsByName()
returns a DOM element (the first one to match the selector), not a DOM element collection. And instead of using the name
, let's use a selector that is really unlikely to be found on any other element in your page:
let el = document.querySelector('[accept=".jpg,.jpeg,.gif,.png"]');
el.id = 'mahFile'
let el = document.querySelector('[accept=".jpg,.jpeg,.gif,.png"]');
el.id = 'mahFile';
console.log(el.getAttribute('id'))
<input type="file" name="file" accept=".jpg,.jpeg,.gif,.png">
That's how I would select that element.
But, as Jaromanda realized, your problem is that, in fact, the element is not yet present in DOM at the time you run your script. Depending on how much time it takes to load that script, the following might or might not work:
Since you don't have the ability to call a function when your script loads, you might as well check if the element was added to the page. If it hasn't, try again after another second:
<script type="text/javascript">
function maybeAddId() {
let el = document.querySelector('[accept=".jpg,.jpeg,.gif,.png"]');
if (el) {
el.id = 'mahFile';
console.log('Success!', el.getAttribute('id'))
} else {
console.log('element is not yet in DOM...')
setTimeout(maybeAddId, 1000);
}
}
maybeAddId();
</script>
<input type="file" name="file" accept=".jpg,.jpeg,.gif,.png">
Feel free to run it more often than 1 second.