1
var div = document.createElement('div');
div.innerHTML = htmlString 
var obj = {};
obj.doctors = div.getElementById('doctors');

Is there a sensible way to find an ID within an element which is not yet attached to the DOM? Don't want to use JQuery here.

userqwert
  • 2,193
  • 5
  • 28
  • 50
  • Possible duplicate of [Converting HTML string into DOM elements?](http://stackoverflow.com/questions/3103962/converting-html-string-into-dom-elements) – Mike Cluck Mar 22 '16 at 16:56
  • 1
    that's not what I'm asking at all – userqwert Mar 22 '16 at 16:59
  • The only way you can query by ID is if you have a DOM. Using the DOM parser, you can convert `unformattedString` into a DOM then retrieve the correct element. Otherwise, you'll have to insert the newly created `div` into the main DOM. I suppose the final alternative would be to parse it and generate the nodes yourself but then you're just rewriting `DOMParser`. – Mike Cluck Mar 22 '16 at 17:00
  • You'd have to use a string search on the unformatted string. But that's not necessarily sensible. – David L Mar 22 '16 at 17:01
  • guys, hes asking for a **DOM node** that is not attached, not a html string... – LJᛃ Mar 22 '16 at 17:01
  • @MikeC so I can have multiple DOMs? – userqwert Mar 22 '16 at 17:02
  • 1
    @userqwert Sure, you have the main DOM where everything is rendered then you can create other DOMs in memory. – Mike Cluck Mar 22 '16 at 17:02
  • 1
    @MikeC neat thanks – userqwert Mar 22 '16 at 17:03

1 Answers1

2

Two ways:

  1. Create a DocumentFragment, attach your node to it and use getElementById:

    var domFragment = new DocumentFragment();
    domFragment.appendChild(div);
    var elem = domFragment.getElementById("yourid");
    
  2. Use query selector:

    var elem = div.querySelector("#yourid");
    
LJᛃ
  • 7,655
  • 2
  • 24
  • 35