How to replace list item content using jQuery?

16,454

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>
Share:
16,454
Miles Pfefferle
Author by

Miles Pfefferle

I am a graphic designer, photographer, and web designer.

Updated on June 08, 2022

Comments

  • Miles Pfefferle
    Miles Pfefferle almost 2 years

    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>