-2

Why the code below doesn't work, but It will work after I use before() and after() to replace prepend and append.

<!DOCTYPE html>
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
  $("#btn1").click(function(){
    $("img").prepend("<b>Before</b>");
  });

  $("#btn2").click(function(){
    $("img").append("<i>After</i>");
  });
});
</script>
</head>

<body>
<img src="/images/logo.png" >
<br><br>
<button id="btn1">Insert before</button>
<button id="btn2">Insert after</button>
</body>
</html>

Thanks,
Ethan
miken32
  • 42,008
  • 16
  • 111
  • 154
Ethan
  • 15
  • 5

2 Answers2

4

The <img /> is an empty tag, which means, nothing can be appended or prepended. So you need to either insert the new HTML before it or after it. That's why neither append() nor prepend() works, but before() works, because, it puts the content before <img tag and not inside it.

Better example with div:

<!-- Our Target -->
<div class="myDiv">Hello, World!</div>

<!-- Prepend("Hi: ") -->
<div class="myDiv">Hi: Hello, World!</div>

<!-- Append(" - Praveen ") -->
<div class="myDiv">Hello, World! - Praveen</div>

<!-- Before("Hi:) -->
Hi:
<div class="myDiv">Hello, World!</div>

Hope the above clarifies you about the three functions.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

Because prepend tries to place it in the <img> tag before all the content, and before() places it before the <img> tag.

L Ja
  • 1,384
  • 1
  • 11
  • 22