Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add attribute without value with Nokogiri

Tags:

ruby

nokogiri

I'm trying to add the attribute autoplay to an iframe. However, this attribute is only a markup, it does not have a value:

<iframe src="..." autoplay></iframe

In Nokogiri to add an attribute its like:

iframe = Nokogiri::HTML(iframe).at_xpath('//iframe')
iframe["autoplay"] = ""
puts iframe.to_s

---------- output ----------

"<iframe src="..." autoplay=""></iframe>"

Does Nokogiri has such a way to do this or should I remove /=""/ with an regex at the end?

Thanks

like image 759
Luccas Avatar asked Nov 09 '22 13:11

Luccas


1 Answers

Nokogiri cannot do what you want, out of the box.

  • Option 1: use your regex solution.

  • Option 2: HTML syntax says that a boolean attribute can be set to its own value, thus this is legal and fine to do in your code:

    iframe["autoplay"] = "autoplay"
    

    Output:

    <iframe src="..." autoplay="autoplay"></iframe>
    
  • Option 3: alter the Nokogiri gem code.

    $ edit nokogiri-1.6.6.2/lib/nokogiri/html/element_description_defaults.rb
    

    Find this line:

    IFRAME_ATTRS = [COREATTRS, 'longdesc', 'name', ...
    

    And insert autoplay:

    IFRAME_ATTRS = [COREATTRS, 'autoplay', 'longdesc', 'name', ...
    

    Now Nokogiri will treat autoplay as a binary attribute, as you want.

    I'm creating a pull request for your idea, to add this feature to Nokogiri for everyone:

    https://github.com/sparklemotion/nokogiri/pull/1291

like image 86
joelparkerhenderson Avatar answered Dec 25 '22 10:12

joelparkerhenderson