Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – setAttribute – onclick

I am newbie in js. I have a problem with one issue.
I want to set use my function on my parahraph to set the attribiutes..

<body>
<p id=1>Paragraph 1</p>
<p id=2>Paragraph 2</p>
<p id=3>Paragraph 3</p>
</body>

<script>
function myFunction(id) {
    document.getElementById(id).style.color = "green";
}
initAll();
function initAll() {
    var elements = document.getElementsByTagName('p');
    var n;
    for (n = 0; n < elements.length; ++n) {
        elements[n].setAttribute("onclick", "myFunction(%d)", n);
    }

}
</script>

In the output I have something like that:
output

I can’t provide the references of variable n.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Maybe is there better way to set the attribiutes?

>Solution :

From what I understand you want to attach an event listener( for click event ) on each p element and execute that function when clicking on the elements.

To attach an event listnener on an element you can use addEventListener.

To get the ID and pass it as a param to your function you can use getAttribute

You can also use const and let instead of var. Read here -> var vs let or here var let const

function myFunction(id) {

    document.getElementById(id).style.color = "green";
}

function initAll() {
    const elements = document.getElementsByTagName('p');

    for (let n = 0; n < elements.length; ++n) {
        const elementId = elements[n].getAttribute("id")
        elements[n].addEventListener("click", function(){
            myFunction(elementId)
        });
    }
}
initAll() 
<p id=1>Paragraph 1</p>
<p id=2>Paragraph 2</p>
<p id=3>Paragraph 3</p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading