How to add attribute without value using Nokogiri

I am trying to add an attribute autoplayin an iframe. However, this attribute is only markup, it does not matter:

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

In Nokogiri, add the attribute as follows:

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

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

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

Does Nokogiri have such a way to do this, or do I need to delete /=""/using the regex at the end?

thank

+4
source share
1 answer

Nokogiri cannot do what you want out of the box.

  • Option 1: use your regular expression.

  • Option 2: The HTML syntax says that the boolean attribute can be set to its own value, so this is legal and beautiful in your code:

    iframe["autoplay"] = "autoplay"
    

    Conclusion:

    <iframe src="..." autoplay="autoplay"></iframe>
    
  • Option 3: Change the Nokogiri Jewel Code.

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

    Find this line:

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

    :

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

    Nokogiri autoplay , .

    pull , Nokogiri :

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

+1

Source: https://habr.com/ru/post/1589326/


All Articles