0

Essentially, I'm using JavaScript to add <li> tags with content inside them dynamically to a <ul>. This works fine and great, except when I try to select an element inside that <li> tag via it's ID or Class, I get an errors saying it's not a valid selector. I assume this is because it was added dynamically? Is there any way around this?

Here is code creating the new items:

var newNodeLi = document.createElement('li');
        newNodeLi.addEventListener("click", function() { selectNodeEdit(event); }, false);

        newNodeLi.innerHTML = `<span id="node|${String(newNodeID)}" class="tf-nc"><p id="nodeText|${String(newNodeID)}" class="orgText">Title</p><p id="nodeText|${String(newNodeID)}" class="orgText">Employee</p></span>`
        depTopLevel.appendChild(newNodeLi);

depTopLevel being the <ul> its added to.

I'm simply using document and querySelector to select the elements nested inside the dynamically added <li> but again, will just return an error about an invalid selector even though I have done the sanity check of making sure yes, the id and classes are set correctly and I'm trying to access them correctly

document.querySelector('#node|' + String(nodeID))

Above is an example of how I would select the elements.

Anyways, I assume this is simply because it was added to the DOM dynamically, and as such I can't access it normally with document. Is there any way to select dynamically added DOM elements?

  • You shouldn't need to use `String(newNodeID)`? – evolutionxbox Aug 16 '23 at 13:57
  • 1
    Invalid Selector means the selector you used for the query is invalid, in this case using the pipe `|` is an invalid character – Patrick Evans Aug 16 '23 at 13:57
  • 1
    *"I assume this is because it was added dynamically?"* - Don't assume. [Test](https://jsfiddle.net/ojwfhm16/). – David Aug 16 '23 at 14:01
  • You would need to _escape_ such special characters like the pipe symbol in your CSS selectors - https://mathiasbynens.be/notes/css-escapes has the details. Do yourself a favor, and just use an allowed character instead - like f.e. `node-xyz` instead of `node|xyz` – CBroe Aug 16 '23 at 14:02
  • @CBroe thank you! This was it. I feel silly. Sorry everyone, getting back into programming again, ended up missing something as simple as this – ColtTheNark Aug 16 '23 at 14:22

0 Answers0