2

Example of code:

var new_node = document.createElement('div'); new_node.id = 'parent_1'; var html = '<div id="select_1">hey</div>'+ '<div id="select_2">hey</div>'; new_node.innerHTML = html; 

example of code with DOMParser

var parser = new DOMParser(); new_node.appendChild(parser.parseFromString(html, "text/html").documentElement); 

in whatever way, I cannot access to the element through

console.log(document.getElementById('select_1')); //null // but I can with the DOM-like node (appended to the document) console.log(document.getElementById('parent_1')); //correct 

What options do I have? I would not want to write the select_x nodes in a DOM-like style, since html code written in that way would lose all understand-ability IMHO

*The parent_1 node is appended onto a real HTML node such as document.getElementById('html_element').parentElement.appendChild(parent_1);

EDIT: solved By using querySelector, for example

var parser = new DOMParser(); var temp = parser.parseFromString(html, "text/html").documentElement; console.log(temp.querySelector('#select_1')); //correct new_node.appendChild(temp); 
8
  • 1
    Hi there! This would be a much better question if you could include your code :) Commented Aug 28, 2015 at 14:00
  • [better now] . . Commented Aug 28, 2015 at 14:09
  • 3
    why if=" and not id=" is that just a typo or the real issue here? Commented Aug 28, 2015 at 14:21
  • 1
    Div select_1 is inside new_node. Your code doesn't show that you insert new_node into the document, so document.getElementByid can never work until you do. You have to use new_node.getElementById() if you want to get the select_1 before you append new_node to the document. Commented Aug 28, 2015 at 14:21
  • 1
    @Shilly - yep I was just going to comment the same thing - which along with the getElementById('select_1') is selecting a non-existent element even if it were appended to the document. Commented Aug 28, 2015 at 14:22

1 Answer 1

4

Solved By using querySelector (see edited question), for example

var parser = new DOMParser(); var temp = parser.parseFromString(html, "text/html").documentElement; console.log(temp.querySelector('#select_1')); //correct new_node.appendChild(temp); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.