Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
147
rated 0 times [  151] [ 4]  / answers: 1 / hits: 17056  / 11 Years ago, tue, october 29, 2013, 12:00:00

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>

More From » jquery

 Answers
32

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>

[#74660] Monday, October 28, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
madelyn

Total Points: 449
Total Questions: 100
Total Answers: 100

Location: Seychelles
Member since Fri, May 7, 2021
3 Years ago
madelyn questions
Wed, Jul 28, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
Sat, Nov 7, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;