2017-05-04 25 views
0

我試圖在h3標記後添加一行文本。如何使用Nokogiri在div後添加文本

我的出發HTML是這樣的:

<h3>hi</h3> 

與任何其他標記,或文檔類型。我希望我的結局HTML看起來像這樣:

<h3>hi</h3> 
{% include 'tester-credit-button' %} 

我試過如下:

page = Nokogiri::HTML::DocumentFragment.parse("my_page.html") 
title = page.at_css("h3") 
#tried this first 
title.children.after("\n{% include 'tester-credit-button' %}") 

#then this 
title << "\n{% include 'tester-credit-button' %}" 

#then this 
title.after("\n{% include 'tester-credit-button' %}") 

#then this 
text_node = Nokogiri::XML::Text.new("\n{% include 'tester-credit-button' %}" 
, page) 
title.add_child(text_node) 

回答

-2

你讓太辛苦:

require 'nokogiri' 
doc = Nokogiri::HTML::DocumentFragment.parse('<h3>hi</h3>') 
doc.at('h3').next = "\n{% include 'tester-credit-button' %}" 
puts doc.to_html 

# >> <h3>hi</h3> 
# >> {% include 'tester-credit-button' %} 

返回到您的代碼。 ...

page = Nokogiri::HTML::DocumentFragment.parse("my_page.html") 

是錯誤的。您可以測試,很容易使用:

page.to_html # => "my_page.html" 

the documentation,當它說:「tags」這意味着你有一些HTML或XML來傳遞:

page = Nokogiri::HTML::DocumentFragment.parse("<p><span>foo</span></p>") 
page.to_html # => "<p><span>foo</span></p>" 

我建議學習HTML和XML如何因爲你的實驗建議你不理解解析文檔的節點,它們的可能類型以及它們的子節點和兄弟節點的概念。 Nokogiri的教程將有所幫助,同樣可以在SO上搜索標籤並閱讀各種問題和答案。 Nokogiri功能強大且易於使用,一旦你將這個概念帶到你的腰帶上。

+0

與我的HTML,節點或節點集的結構無關。非常感謝你的建議。 – ToddT

相關問題