javascript - Retrieving an element nested within another element using id -


i have following code parses html markup dom object.

var html_str = '<div id="body-wrapper">\         <div id="container-1">\             <p>this first container - line 1</p>\             <p>this first container - line 2</p>\             <p><img src="assets/img/pull_1.jpg"></p>\         </div>\         <div id="container-2">\             <p>this second container - line 1</p>\             <p>this second container - line 2</p>\             <p>this second container - line 3</p>\             <p><img src="assets/img/pull_2.jpg"></p>\         </div>\         <div id="container-3">\             <p>test</p>\             <p><img src="assets/img/pull_3.jpg"></p>\         </div>\     </div>';  var elem_obj = document.createelement("div"); elem_obj.innerhtml = html_str; 

how element id == container-1 within elem_obj? vanilla javascript , other elem_obj.queryselector('#container-1') because need support ie below version 8.

thanks.

as said in comments, apologies arguing vehemently on incomplete data. while true old ie use getelementbyid in documentfragment, not true newer browsers, hybrid strategy needed best compatibility.

var html = '<div id="body-wrapper">\    <div id="container-1">\      <p>this first container - line 1</p>\      <p>this first container - line 2</p>\      <p><img src="#"></p>\    </div>\    <div id="container-2">\      <p>this second container - line 1</p>\      <p>this second container - line 2</p>\      <p>this second container - line 3</p>\      <p><img src="#"></p>\    </div>\      <div id="container-3">\      <p>test</p>\      <p><img src="#"></p>\    </div>\  </div>';      // http://stackoverflow.com/a/1643512/240443  function getelementbyidfromnode(node, id) {    (var = 0; < node.childnodes.length; i++) {      var child = node.childnodes[i];      if (child.nodetype !== 1) // element_node        continue;      if (child.id === id)        return child;      child = getelementbyidfromnode(child, id);      if (child !== null)        return child;    }    return null;  }  // based on http://stackoverflow.com/a/1643383/240443  function getelementbyidfromstring(html, id) {    var div = document.createelement("div");    div.innerhtml = html;    // new browsers    if (div.queryselector) {      return div.queryselector("#" + id);    }    // old ie    var frag = document.createdocumentfragment();    if (frag.getelementbyid) {      frag.appendchild(div);      return frag.getelementbyid(id);    }    // else in case    return getelementbyidfromnode(div, id);  }  var container3 = getelementbyidfromstring(html, "container-3");  console.log(container3);


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -