title: Adding a node using Nokogiri
body: <p>I have an HTML string (for instance <code>&lt;div class="input"&gt;hello&lt;/div&gt;</code>) and I want to add a node only if the HTML tag in the string is a <code>label</code> (for instance <code>&lt;label&gt;Hi&lt;/label&gt;</code>).</p>
  
  <pre><code>doc = Nokogiri::XML(html)
  
  doc.children.each do |node|
    if node.name == 'label'
      # this code gets called
      span = Nokogiri::XML::Node.new "span", node
      span.content = "hello"
  
      puts span.parent 
      # nil
  
      span.parent = node
      # throws error "node can only have one parent"
    end
  end
  
  doc.to_html # Does not contain the span.
  </code></pre>
  
  <p>I cannot for the life of me understand what I'm doing wrong, any help would be <strong>greatly</strong> appreciated.</p>
  
  <p><strong>Edit</strong>: This solved my problem, thanks for the answers!</p>
  
  <pre><code># notice DocumentFragment rather than XML
  doc = Nokogiri::HTML::DocumentFragment.parse(html_tag)
  doc.children.each do |node|
    if node.name == 'label'
      span = Nokogiri::XML::Node.new "span", doc
      node.add_child(span)
    end
  end
  </code></pre>