-1

All:

I am pretty new to HTML, when I directly use something like:

<div title="hello&#10;world" >GO</div>

It works as expected which breaks the "world" into next line, but when I try:

var a = "&#10;";
$("#go")
    .attr("title", "hello"+ a +"world");

Then it will treat that line break as plain text. I wonder how can I connect string as title attribute?

Thanks

dabadaba
  • 9,064
  • 21
  • 85
  • 155
Kuan
  • 11,149
  • 23
  • 93
  • 201
  • Your top tags are angularjs, reactjs and javascript, yet you're new to HTML? Please explain how that happens? haha – dabadaba Apr 14 '16 at 21:59
  • @dabadaba 'The more you know, the more you know you don't know.' -- Aristotle – Kuan Apr 14 '16 at 22:00

2 Answers2

2

The escape trick mentioned here is a very common approach to dealing with encoding HTML issues. It involves creating a "phantom" <div> and storing your preferred HTML content within it and then using the text() function to retrieve it :

// Store your new line character
var newLine = '&#10';
// Create a phantom <div> elment and set the HTML content for it
// then return the text
var title = $('<div/>').html('hello' + newLine + 'world').text();
// Finally set the attribute to the text
$("#go").attr("title", title);

You can see an example of it in action here :

enter image description here

Community
  • 1
  • 1
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
1

jQuery handles escaping for you. You can simply do:

$("#go")
    .attr("title", "hello\nworld");
arcyqwerty
  • 10,325
  • 4
  • 47
  • 84