3

I'm trying to make a button that will replace the content of a li. I've searched other answers on here, but I get this error: Uncaught TypeError: Object li#element2 has no method 'replaceWith'

I've tried replaceWith, .html, and .text, but they all have the same Here's my page:

<html>
<head>

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script>
$(document).ready(function(){
$("#theButton").click(function(){
("li#element2").replaceWith("This is the second element")
});
});
</script>

</head>
<body>

<h1 id="header">The document header.</h1>


<p>Value: <input type="text" id="theInput" value="" size=10>


<ul id="theList">
<li id="element1">Element 1
<li id="element2">Element 2
<li id="element3">Element 3
</ul>

<div id="theDiv"></div>

<input type="button" id="theButton" value="click me!""></p>


</body>
</html>
1
  • 1
    Do not forget to close your <li> tags. ;) Commented Oct 29, 2013 at 1:18

1 Answer 1

12

Typo

missing $ sign

$("#element2").replaceWith("This is the second element");
^

fiddle DEMO


Commented by NicoSantangelo

You also don't need $("li#element2") it will be faster with $("#element2") as id is unique so don't have to use tag selector with it.


Better use .text()

fiddle DEMO

$(document).ready(function () {
    $("#theButton").click(function () {
        $("#element2").text("This is the second element")
    });
});


Correct your markup close li tags

<ul id="theList">
  <li id="element1">Element 1</li>
  <li id="element2">Element 2</li>
  <li id="element3">Element 3</li>
</ul>
Sign up to request clarification or add additional context in comments.

2 Comments

"li#element2" === "#element2" just more "expensive"
@NicoSantangelo ty i didn't see that lol ..!! But updated answer now.

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.