3

Consider this for example:

<div>
  A&
  <br>
  B
</div>

If I use $('div').html(), it returns A&amp;<br>B. It converts A& into A&amp; which I do not want.

If use use $('div').text(), it returns A&B. It ignores the <br> which I do not want either.

I'm looking for a way to get all the html inside the div without parsing it and without skipping over the tags like <br> either.

This is the result I want: A&<br>B. How do I achieve that?

Harsha Reaper
  • 129
  • 1
  • 10
  • 3
    And what's the problem with `&` ? That would be the correct response to getting the HTML – adeneo Jan 16 '17 at 20:12
  • That's correct, you should stick to `&` – Mateusz Woźniak Jan 16 '17 at 20:14
  • I need to get the content as it is. It will be used as input for C++ programs, etc. So I can't have it changed from & to & because the program would give a different output if the input changes from & to & – Harsha Reaper Jan 16 '17 at 20:16
  • 1
    This can be done with a little vanilla js. Check out this answer. http://stackoverflow.com/a/7394787/5937428 – amflare Jan 16 '17 at 20:21
  • @tbirrell answer the question then... – Legends Jan 16 '17 at 20:23
  • @Legends - That would just be me copying someone else's work though. – amflare Jan 16 '17 at 20:27
  • @Legends If the answer is in another question, it's likely that the question is a duplicate. Please don't suggest that people copy answers. – Heretic Monkey Jan 16 '17 at 20:30
  • @MikeMcCaughan, then mark it as a duplicate, if it's the same question! You have the reputation to do that. – Legends Jan 16 '17 at 20:32
  • As do you. You can click the flag link and mark it as a duplicate as well. – Heretic Monkey Jan 16 '17 at 20:34
  • @MikeMcCaughan What actually happens with points received for answers on duplicate questions like the one below? And what happens with the question, will it get deleted? – Legends Jan 16 '17 at 20:53
  • From [Why are some questions marked as duplicate?](http://stackoverflow.com/help/duplicates): *Some duplicate questions may eventually be deleted, but often they are left as a signpost pointing people towards the canonical answer to that question.* Reputation points are kept as is. – Heretic Monkey Jan 16 '17 at 20:59
  • Points are kept? This motivates people to copy and post already existing answers as we can see here... Thanks for the info! – Legends Jan 16 '17 at 21:05

2 Answers2

4

function decodeEntities(encodedString) {
    var textArea = document.createElement('textarea');
    textArea.innerHTML = encodedString;
    return textArea.value;
}
console.log(decodeEntities($('div').first().html()))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  A&
  <br>
  B
</div>

EDIT

See also node.innerText https://developer.mozilla.org/en-US/docs/Web/API/Node/innerText

tommybananas
  • 5,718
  • 1
  • 28
  • 48
2

This is really a "hack" but it does work.

$("<textarea>").html($("div").html()).val()
VKK
  • 882
  • 7
  • 19