How to manipulate DOM with Ruby on Rails

前端 未结 3 1820
逝去的感伤
逝去的感伤 2021-02-03 14:40

As the title said, I have some DOM manipulation tasks. For example, I want to: - find all H1 element which have blue color. - find all text which have size 12px. - etc..

3条回答
  •  不思量自难忘°
    2021-02-03 15:33

    If what you're trying to do is manipulate HTML documents inside a rails application, you should take a look at Nokogiri.

    It uses XPath to search through the document. With the following, you would find any h1 with the "blue" css class inside a document.

    require 'nokogiri'
    require 'open-uri'
    
    doc = Nokogiri::HTML(open('http://www.stackoverflow.com'))
    doc.xpath('//h1/a[@class="blue"]').each do |link|
        puts link.content
    end
    

    After, if what you were trying to do was indeed parse the current page dom, you should take a look at JavaScript and JQuery. Rails can't do that.

提交回复
热议问题