2017-05-04 7 views
0

h3タグの後にテキストの行を追加しようとしています。いいえ他のタグ、またはドキュメントタイプとNokogiriを使用してdivの後にテキストを追加する方法

<h3>hi</h3> 

マイ開始HTMLはこれです。私は私の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") 

が間違っています。あなたは簡単に使用しているをテストすることができます:私はHTMLとXMLがどのように勉強をお勧めします

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

page.to_html # => "my_page.html" 

the documentationでは、それが言うとき、「tagsは、」それはあなたには、いくつかのHTMLまたはXMLに合格する必要があるということパースされたドキュメントのノード、その可能なタイプ、およびその子と兄弟のアイデアを理解できないことを示唆しているためです。 Nokogiriのチュートリアルでは、ここでタグを検索したり、さまざまな質問と回答を読むのに役立ちます。 Nokogiriはあなたのベルトの下でそのコンセプトを取得すると、使いやすく強力です。

+0

HTML、ノード、またはノードセットの構造とは関係ありません。しかし、それを提案していただきありがとうございます。 – ToddT

関連する問題