0

How, in JavaScript, can I search for a child element from this code?

(Sorry, I'm not an expert with naming things or making my code look "neat and organized.")

var thisWin = document.querySelector("#tempWindow").cloneNode(true);
bodyOrDocument = (document.documentElement || document.body)
bodyOrDocument.appendChild(thisWin)

I am cloning an element, and the clone has no classes or IDs, so I tried this:

windowId = random(0, 10000000).toString();
thisWin.setAttribute("id", windowId)
thisWiniFrame = document.querySelector("#" + windowId + " iframe");

But I get this error in the console:

Uncaught DOMException: Failed to execute 'querySelector' on 'Document': '#8722143 iframe' is not a valid selector.

I know the tag names are not reliable, but it's only for testing purposes anyways, so it's not really that important to me.

Anyways, does anybody know why is this error showing up? I have been stuck on this for a while.

1 Answers1

0

From here:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

thus the error

Alberto Sinigaglia
  • 12,097
  • 2
  • 20
  • 48
  • https://jsfiddle.net/rL4mdx3q/ With the caveat that `getElementById` doesn't care. – Taplar Aug 07 '20 at 22:35
  • This is the HTML4 spec. In HTML5 an ID can begin with a number, although CSS might throw a fit. https://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html – j08691 Aug 07 '20 at 22:35
  • @j08691 yep: https://drafts.csswg.org/selectors-3/#id-selectors -> https://www.w3.org/TR/CSS21/syndata.html#value-def-identifier -> **In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit** – Alberto Sinigaglia Aug 07 '20 at 22:39