0

Create an element and pass it an innerHTML string.

let mydiv = document.createElement('div');
mydiv.innerHTML = "<div> <p>Intro</p> </div> <div id='greet'> <p>Hello Example</p> </div>";
console.log(mydiv.getElementByID("greet"))

.. How do I get the element with id='greet'?

mydiv.getElementbyID('greet')   //doesn't work.
mplungjan
  • 169,008
  • 28
  • 173
  • 236
RemyG
  • 187
  • 2
  • 4

5 Answers5

0

Assuming u have jquery

$(mydiv).find("#greet");
Rajkumar Somasundaram
  • 1,225
  • 2
  • 10
  • 20
0

With your code, you can use Element.querySelector instead

You do have a few issues

  1. misspelling getElementByID - should be getElementById
  2. you cannot use Element.getElementById - you can use document.getElementById after inserting the new div into the DOM

querySelector

let mydiv = document.createElement('div');
mydiv.innerHTML = "<div> <p>Intro</p> </div> <div id='greet'> <p>Hello Example</p> </div>";
console.log(mydiv.querySelector("#greet"))

Or jQuery:

let $myDiv =$('<div/>');
$myDiv.html("<div> <p>Intro</p> </div> <div id='greet'> <p>Hello Example</p> </div>");
console.log($myDiv.find("#greet"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0
mydiv.querySelector('#greet')

This is one very subtle difference between these selectors. With query selector, we can query string templates. Inspired from here.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
RemyG
  • 187
  • 2
  • 4
0

Try the following way,

for (var child = mydiv.firstChild; child; child = child.nextSibling) {
   if(child.id == "greet") {
      console.log(child);
   }
}
Madhavan.V
  • 825
  • 1
  • 6
  • 14
0

getElementById is on document and not on a node. So you can always use queryselector like this.

let mydiv = document.createElement('div');
mydiv.innerHTML = "<div> <p>Intro</p> </div> <div id='greet'> <p>Hello Example</p> </div>";
console.log(mydiv.querySelector("#greet"));
Karthik RP
  • 1,028
  • 16
  • 26
  • 1
    My bad, Didn't the same when I started typing my answer. Sucks that I took nearly 5 minutes to answer the question. – Karthik RP Nov 14 '17 at 09:58