<body>
<p class="one" id="p_1" name="p_1">3</p>
<p class="one" id="p_2" name="p_2">7</p>
<p class="one" id="p_3" name="p_3">2</p>
<p class="one" id="p_4" name="p_4">4</p>
<p class="one" id="p_5" name="p_5">1</p>
<button onclick="findMax()">findMax</button>
<script type="text/javascript">
function findMax(){
const elems = document.querySelectorAll('.one');
elems.forEach(function(val, index) {
elems[index].textContent = index+1;
});
}
</script>
</body>
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>
) will also add backticks around text.
Note: Backticks are not single quotes.
Ceiling in a sorted array · Count number of occurrences (or frequency) in a sorted … Queries for maximum and minimum difference between Fibonacci numbers in … Find the maximum element in an array which is first increasing and then decreasing … We can traverse the array and keep track of maximum and element .
querySelectorAll
gives you a list of DOM elements (following isn’t code, just a description of what you have)
[p_1, p_2, p_3, p_4, p_5]
For each of those elements, you are setting the textContent to the index + 1, so
p_1 -> index 0 -> set to 1
p_2 -> index 1 -> set to 2
p_3 -> index 2 -> set to 3
p_4 -> index 3 -> set to 4
p_5 -> index 4-> set to 5
So you get
<p class="one" id="p_1" name="p_1">1</p>
<p class="one" id="p_2" name="p_2">2</p>
<p class="one" id="p_3" name="p_3">3</p>
<p class="one" id="p_4" name="p_4">4</p>
<p class="one" id="p_5" name="p_5">5</p>
You aren’t looking at what the value is at all (ie the textContent
of each element), you’re just replacing it with a number based on the index (afaics, you have no need to even know what the index is, it’s not relevant)