search

Home  >  Q&A  >  body text

How to access specific element without using class or id?

<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粉106301763P粉106301763537 days ago540

reply all(2)I'll reply

  • P粉244730625

    P粉2447306252023-09-01 14:27:59

    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.

    reply
    0
  • P粉706038741

    P粉7060387412023-09-01 14:19:04

    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>

    reply
    0
  • Cancelreply