-1

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.

Maybe is there better way to set the attribiutes?

  • Why do you expect sprintf-like format strings to work here...? It's unclear to my how you got this idea, I don't see any evidence of it ever being supported by `setAttribute`. Please refer to the docs of each function/method you use as to how it works (and how it doesn't). I think `console` logging functions are the only methods like that. – CherryDT Nov 21 '21 at 11:36

3 Answers3

1

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>
Mihai T
  • 17,254
  • 2
  • 23
  • 32
0

1- HTML IDs can't start with a numbers.

<p id=myID1>Paragraph 1</p>

2- Concatenate the string with n

"" + (n+1) + ""

3- Since the ID is a string, you have to close it inside single quotes

"myFunction('myID" + (n+1) + "')"

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

function initAll() {
  var elements = document.getElementsByTagName('p');
  var n;
  for (n = 0; n < elements.length; ++n) {
    elements[n].setAttribute("onclick", "myFunction('myID" + (n+1) + "')");
  }
}

initAll();
<body>
  <p id=myID1>Paragraph 1</p>
  <p id=myID2>Paragraph 2</p>
  <p id=myID3>Paragraph 3</p>
</body>
Baro
  • 5,300
  • 2
  • 17
  • 39
  • Why can't ID's start with numbers ? Why concatenate when you can use template strings ? – Mihai T Nov 21 '21 at 11:46
  • @MihaiT ID can't start with numbers in HTML4, but actually checking in HTML5 is no longer a problem. And why not a concatenated string, it's a preference. – Baro Nov 21 '21 at 12:10
0

You're trying to set the onclick attribute to your paragraph elements and assign them to your myFunction.

Since your ids start from 1, you've to write (n + 1) inside the body of for loop (loop variable n starts from 0)

In Javascript, there are no formatting specifiers (%d) available like in C. So you just do string concatenation using the + operator.

So, the line should be,

for (var n = 0; n < elements.length; ++n) {
   var index = n + 1;
   elements[n].setAttribute("onclick", "myFunction(" + index + ")");
}

It'll work fine now.

But this is not a way people use to add event listeners in JavaScript. I recommend checking out forEach and addEventListener methods in MDN.

https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Hari Ram
  • 56
  • 5