getElementById() wildcard

后端 未结 6 2193
北荒
北荒 2020-11-28 11:37

I got a div, and there i got some childnodes in undefined levels.

Now I have to change the ID of every element into one div. How to realize?

I thought, becau

相关标签:
6条回答
  • 2020-11-28 12:16

    In one of the comments you say:

    (...) IE is anyway banned on my page, because he doesn't get it with CSS. It's an admin tool for developer, so only a few people, and they will anyway use FF

    I think you should follow a different approach from the beginning, but for what it's worth, in the newer browsers (ok, FF3.5), you can use document.querySelectorAll() with which you can get similar results like jQuery:

    var elements = document.querySelectorAll('[id^=foo]');
    // selects elements which IDs start with foo
    

    Update: querySelectorAll() is only not supported in IE < 8 and FF 3.0.

    0 讨论(0)
  • 2020-11-28 12:26

    I don't think so wildcards are allowed in getelementById. Instead you can have all the child nodes of your respective DIV using:

    var childNodeArray = document.getElementById('DIVID').childNodes;
    

    This'll give you an array of all elements inside your DIV. Now using for loop you can traverse through all the child elements and simultaneously you can check the type of element or ID or NAME, if matched then change it as you want.

    0 讨论(0)
  • 2020-11-28 12:28

    Not in native JavaScript. You have various options:

    1) Put a class and use getElementsByClassName but it doesn't work in every browser.

    2) Make your own function. Something like:

    function getElementsStartsWithId( id ) {
      var children = document.body.getElementsByTagName('*');
      var elements = [], child;
      for (var i = 0, length = children.length; i < length; i++) {
        child = children[i];
        if (child.id.substr(0, id.length) == id)
          elements.push(child);
      }
      return elements;
    }
    

    3) Use a library or a CSS selector. Like jQuery ;)

    0 讨论(0)
  • 2020-11-28 12:34

    jQuery allows you to find elements where a particular attribute starts with a specific value

    In jQuery you would use

    $('[id^="path_test_"]')
    
    0 讨论(0)
  • 2020-11-28 12:34

    You should not change ID of element to ID of other existing element. It's very wrong, so you better re-think your core logic before going on.

    What are you trying to do exactly?

    Anyway, to get all elements with ID starting with something, use jQuery as suggested before, if you can't it's also possible using pure JavaScript, let us know.

    0 讨论(0)
  • 2020-11-28 12:40

    Try this in 2019 as a wildcard.

    document.querySelectorAll("[id*=path_test_]")
    
    0 讨论(0)
提交回复
热议问题