Luccas
Luccas

Reputation: 4268

How to add attribute without value with 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

Upvotes: 5

Views: 359

Answers (1)

joelparkerhenderson
joelparkerhenderson

Reputation: 35453

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

Upvotes: 1

Related Questions