1

I'm passing a self-closing anchor tag with no text value, just a name:

<% test = '<h4><a name="139-01"/>test</h4>' %>

When I output the value it looks like this:

<h4><a name="139-01"/>test</h4>

Then I try to use .html_safe to output it as an html tag

<%= test.html_safe %>

The resulting code is:

<h4><a name="139-01">test</a></h4>

As you can see above the anchor tag was change from a self-closing tag to a tag that includes the text "test" for some reason. Does anyone know why this is occurring?

If I set the string to:

<% test = '<h4><a name="139-01"></a>test</h4>' %>

It works as expected:

<h4><a name="139-01"></a>test</h4>

The problem is that I don't have access to change the tag in the actual data.

spyderman4g63
  • 2,870
  • 4
  • 18
  • 27
  • 2
    Did you double-check by looking at the HTML source code of the page that Ruby actually added the closing ``? I would argue that a [self-closing hyperlink tag](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Properties) is invalid HTML and therefore guess that the browser just tries its best to understand this invalid html and adds the closing `` tag where it thinks it makes sense. – spickermann Mar 09 '20 at 17:15
  • I found a way to change the input data that resolved the issue but I'd still like to understand why .html_safe changes the markup. – spyderman4g63 Mar 09 '20 at 17:15
  • This question seems to suggset self-closing tags are invalid in HTML5 "HTML5 basically behaves as if the trailing slash is not there. There is no such thing as a self-closing tag in HTML5 syntax." https://stackoverflow.com/questions/3558119/are-non-void-self-closing-tags-valid-in-html5 – spyderman4g63 Mar 09 '20 at 17:18
  • 1
    @spickermann I think your answer is correct. It's the browser changing the tag because it's trying to fix the markup. If I put the markup directly in the browser it displays the "wrong" way. If you would like to make an official answer I will accept it. – spyderman4g63 Mar 09 '20 at 17:21

1 Answers1

3

It is not Ruby on Rails changing your HTML.

A self-closing hyperlink simply is invalid HTML. And it is the browser that tries its best to parse and understand this invalid HTML and the browser adds the closing </a> tag where it thinks it makes the most sense.

Relevant in this context:

spickermann
  • 81,597
  • 8
  • 83
  • 112