1

I'm able to set line break with javascript in an element, but I can't read them.

Example:

<div id="text"></div>

Js:

document.getElementById("text").innerHTML = "Hello <br /> World";
var x = document.getElementById("text").innerHTML;

if(x == "Hello <br /> World")
{
alert('Match');
}

There is no match in my case...

1
  • 1
    Why do you need to do that in the first place? Commented Oct 16, 2014 at 22:38

1 Answer 1

5

It is pretty much never a good thing to get the .innerHTML property from an object and then try to compare it to some exact string. This is because the only contract the browser has is to return to you equivalent HTML, not necessarily the exact same HTML. This may not be a problem if there are no nested DOM elements in what you are requesting, but can often be a problem if there are nested HTML elements.

For example, some versions of IE will change the order of attributes, change the quoting, change the spacing, etc...

Instead, you should either search the actual DOM for what you want or look for only a smaller piece of the HTML which you know can't change or use a search algorithm that is tolerate of changes in the HTML.

As Niels mentioned in a comment, Chrome, IE11 and Firefox all return "Hello <br> World" which you can see for yourself with a simple debugging statement like this:

console.log("'" + x + "'");

Working demo to see for yourself what it shows: http://jsfiddle.net/jfriend00/zc59x2bL/


FYI, your code also contains an error. You need to pass document.getElementById() a string which would be document.getElementById("test"), not document.getElementById(test).

Sign up to request clarification or add additional context in comments.

4 Comments

And most probably it's correctly returning HTML5-style <br> instead of deprecated XHTML-style <br />.
@NielsKeurentjes Shouldn't that totally depend on the document type?
Perhaps they would return <br /> if you correctly triggered XHTML mode with a correct doctype AND a content-type of application/xhtml+xml. Never seen anyone do that though, could be worth a try. In HTML4+5, and in semi-XHTML mode with text/html, the correct notation is <br>.
@NielsKeurentjes I do exactly that :) For me, it feels nice to be "forced" to use strict XML syntax for HTML documents. See also XHTML5 in a nutshell. It doesn't support every HTML5 feature though, but I don't use many anyways.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.