Search code examples
javascriptforeachqueryselectall

Make Function with querySelectAll with forEach


I want to create a javascript querySelectAll with foreach. I need to use this many times. So i want to create a function. But not working. Please help me.

<p id="o">one</p>
<p id="o">two</p>

<script>
function q(x,y) {
document.querySelectorAll(x).forEach(e => { e.y })
}
    
q('#o', innerHTML = 'Working');
</script>

Solution

  • If you want to put some code in a reusable form that you can pass around then it needs to be a function.

    An expression is just going to be evaluated immediately.

    innerHTML = 'Working' will assigned the string to the global variable innerHTML and then the pass the result (the string) to y.

    You need it to be a function and then you need to call it.

    What's more: An ID must be unique in a document. If you want to loop over a group of things then use a class.

    function q(x, y) {
      document.querySelectorAll(x).forEach(y)
    }
    
    q('.o', (element) => element.innerHTML = 'Working');
    <p class="o">one</p>
    <p class="o">two</p>