How to access specific element without using class or id?
P粉106301763
2023-08-31 19:11:14
<p>I am trying to manipulate all HTML tags, the code is as follows: </p>
<pre class="brush:php;toolbar:false;">var elements = document.getElementsByTagName("<*>")</pre>
<p>I want to manipulate the variable <code>elements</code> and modify the labels within it. </p>
<p>The problem is, I need to add an ID or some kind of class name to them. </p>
<p>Is there any other way besides adding ID or class name?
Does the tag have a default special ID or something? </p>
<p>Thank you very much. </p>
<p>Editor:</p>
<p>I used <code>data-id</code> to manipulate these elements. So... now my code looks like this: </p>
<pre class="lang-js prettyprint-override"><code>const dataIDName = "data-spellchecker"
//Initialize data-id
noOfElements;
elements[i].setAttribute(dataIDName, noOfElements);
</code></pre>
<pre class="lang-js prettyprint-override"><code>//Get DOM elements through data-id variables
//dataId is your data-id variable
document.querySelector(`[${dataIDName}="${dataId}"]`);
</code></pre></p>
You can get elements according to the following main ways:
Also, you can use xpath with your own logic.
You can assign it a data-id and a value
You can access it using jquery
Example: