OnKeyPress event do same stuff on multiple inputs I have 3 inputs, when I press enter on them same operations happend. 

This is my code

How would you do this better?

    var __this = this;
    var a = document.getElementById("content").getElementsByTagName("more-content")[0].getElementsByTagName("input")[0];
    var b = document.getElementById("content").getElementsByTagName("more-content")[1].getElementsByTagName("input")[0];
    var b = document.getElementById("content").getElementsByTagName("more-content")[2].getElementsByTagName("input")[0];

    a.onkeypress = function (e) {
        if (e.which == 13) {
            // do same stuff here
        }
    };
    b.onkeypress = function (e) {
        if (e.which == 13) {
            // do same stuff here
        }
    };
    b.onkeypress = function (e) {
        if (e.which == 13) {
            // do same stuff here
        }
    };
There are in fact different ways to handle your request. Here's one I'd like to show as it is:


re-useable (As you can use it on any element everywhere on the page multiple times.)
decoupled from the HTML markup and from CSS classes


HTML

Add a data-*-attribute to the fields where the magic should happen:

&lt;input type="text" name="a" value="a" data-log&gt;


JavaScript


query those specific elements
attach the event handler to each element
run your code


The ES5 way:

var logMe = document.querySelectorAll('[data-log]');

for (var i = 0, max = logMe.length; i &lt; max; i++) {
    logMe[i].addEventListener('keypress', function(event) {
        if (13 == event.which) {
            console.log(this.value);
        }
    }, false);
}


Try it online.

The ES6 way:

let logMe = document.querySelectorAll('[data-log]');

for (let item of logMe) {
    item.addEventListener('keypress', function(event) {
        if (13 == event.which) {
            console.log(this.value);
        }
    }, false);
}


Try it online.



That being said, you can alternatively use CSS classes as well to identify the elements:

&lt;input class="log" type="text" name="a" value="a"&gt;


And select the elements using:

let logMe = document.getElementsByClassName('log');