skip to Main Content

On my page there is an element being appended (by 3rd party JS code) after the closing body tag </body>. I need to select it with querySelector as:

document.querySelector(`div[id*="startOfID"]`); 

and the reason I use * is because the ID changes constantly, but always has the same startOfID.

How am I able to select this element that is outside of </body> but inside </html> using querySelector and *.

2

Answers


  1. make sure you are doing it right.
    here is the example code by which we can achieve the same

    var newElement = document.createElement('div');
    newElement.id = 'startOfID-someRandomNumber';
    document.getElementsByTagName('html')[0].appendChild(newElement);
    
    var newElement = document.createElement('div');
    newElement.id = 'startOfID-someRandomNumber';
    document.getElementsByTagName('body')[0].appendChild(newElement);
    
    Login or Signup to reply.
  2. Unless i misunderstood your question, if you want to get some element by start of the id you need to use ^ instead of *.

    example:
    we have an element with id="test-hajskd"

    we need to call in order to retrieve it:

    const el = document.querySelector("div[id^='test-']"); 
    

    You can learn more about these selectors on this link.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search