How to access specific element without using class or id?
P粉106301763
P粉106301763 2023-08-31 19:11:14
0
2
494
<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>
P粉106301763
P粉106301763

reply all(2)
P粉244730625

You can get elements according to the following main ways:

  1. Id
  2. Class
  3. Name
  4. Tagname

Also, you can use xpath with your own logic.

P粉706038741

You can assign it a data-id and a value

You can access it using jquery

const value = $(event.currentTarget).attr('data-id')

Example:

<button class="submitButton" id="btn1" data-id="1">提交</Button>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template