Reputation: 49
I have this code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>append demo</title>
<style>
p {
background: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<p id="hhh">I would like to say: </p>
<script>
var x = document.getElementById("hhh");
x.prepend("Hello");
</script>
</body>
</html>
How can I use the x
variable to put anything I want in it with the prepend()
function?
Upvotes: 1
Views: 70
Reputation: 936
The simplest way to achieve this is:
$('#hhh').append('Hello');
If you're receiving an error then most likely your link to the jQuery library is broken.
Upvotes: 0
Reputation: 337560
Your x
variable holds a DOMElement, so to use jQuery methods on it you need to put it in to a jQuery object. Try this:
var x = document.getElementById("hhh");
$(x).prepend("Hello");
You can also use jQuery to select the element and turn this in to a one-liner:
$("#hhh").prepend("Hello");
Finally, prepend()
will put the specified string as the first child of the element, in your case resulting in HelloI would like to say:
. From the look of your code you may wish to use append()
instead to put the string at the end of the specified element.
Upvotes: 2