Jquery как изменить содержимое span

Given an HTML document and the task is to change the text content of a span element. There are various methods used to change the span elements which are discussed below jQuery text Method This method set return the text content of specified elements. If this method is used to return

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Given an HTML document and the task is to change the text content of a <span> element. There are various methods used to change the span elements which are discussed below:

    • jQuery text() Method: This method set/return the text content of specified elements. If this method is used to return content, it returns the text content of all matched elements (HTML tags will be removed). If this method is used to set content, it overwrites the content of all matched elements.

      Syntax:

      • It returns the text content.
        $(selector).text()
      • It sets the text content.
        $(selector).text(content)
      • Set text content using a function.
        $(selector).text(function(index, curContent))

      Parameters:

      • content: It is required parameter. It specifies the new text content for the selected elements.
      • function(index, curContent): It is optional parameter. It specifies the function that returns the new text content for the selected elements.
      • index: It returns the index position of element in the set.
      • curContent: It returns the current content of selected elements.
    • jQuery html() Method: This method set/return the content (HTML) of the specified elements. If this method is used to return content, it returns the content of the first matched element. If this method is used to set content, it overwrites the content of all matched elements.

      Syntax:

      • Return content
        $(selector).html()
        
      • Set content
        $(selector).html(content)
        
      • Set content using a function
        $(selector).html(function(index, curContent))
        

      Parameters:

      • content: It is required parameter. It specifies the new text content for the selected elements containing the HTML tags.
      • function(index, curContent): It is optional parameter. It specifies the function that returns the new content for the selected elements.
      • index: It returns the index position of element in the set.
      • curContent: It returns the current HTML content of selected elements.

    Example 1: This example changes the content by using JQuery’s text() method .

    <!DOCTYPE HTML> 

    <html

        <head

            <title

                JQuery | Change the text of a span element

            </title>

            <script src

            </script>

        </head

        <body style = "text-align:center;" id = "body"

            <h1 style = "color:green;"

                GeeksForGeeks 

            </h1

            <span id="GFG_Span" style = "font-size: 15px; font-weight: bold;"

                This is text of Span element. 

            </span>

            <br><br>

            <button

                Change

            </button>

            <p id = "GFG_DOWN" style

                "color:green; font-size: 20px; font-weight: bold;">

            </p>

            <script>

                $('button').on('click', function() {

                    $('#GFG_Span').text("New Span text content");

                    $('#GFG_DOWN').text("Span content changed");

                });     

            </script

        </body

    </html>                    

    Output:

    Example 2: This example changes the content by using JQuery’s html() method .

    <!DOCTYPE HTML> 

    <html

        <head

            <title

                JQuery | Change the text of a span element

            </title>

            <script src

            </script>

        </head

        <body style = "text-align:center;" id = "body"

            <h1 style = "color:green;"

                GeeksForGeeks 

            </h1

            <span id="GFG_Span" style = "font-size: 15px; font-weight: bold;">

                 This is text of Span element. 

            </span>

            <br><br>

            <button

                Change

            </button>

            <p id = "GFG_DOWN" style

                "color:green; font-size: 20px; font-weight: bold;">

            </p>

            <script>

                $('button').on('click', function() {

                    $('#GFG_Span').html("<p>New Span text content</p>");

                    $('#GFG_DOWN').text("Span content changed");

                });     

            </script

        </body

    </html>                    

    Output:

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    Given an HTML document and the task is to change the text content of a <span> element. There are various methods used to change the span elements which are discussed below:

    • jQuery text() Method: This method set/return the text content of specified elements. If this method is used to return content, it returns the text content of all matched elements (HTML tags will be removed). If this method is used to set content, it overwrites the content of all matched elements.

      Syntax:

      • It returns the text content.
        $(selector).text()
      • It sets the text content.
        $(selector).text(content)
      • Set text content using a function.
        $(selector).text(function(index, curContent))

      Parameters:

      • content: It is required parameter. It specifies the new text content for the selected elements.
      • function(index, curContent): It is optional parameter. It specifies the function that returns the new text content for the selected elements.
      • index: It returns the index position of element in the set.
      • curContent: It returns the current content of selected elements.
    • jQuery html() Method: This method set/return the content (HTML) of the specified elements. If this method is used to return content, it returns the content of the first matched element. If this method is used to set content, it overwrites the content of all matched elements.

      Syntax:

      • Return content
        $(selector).html()
        
      • Set content
        $(selector).html(content)
        
      • Set content using a function
        $(selector).html(function(index, curContent))
        

      Parameters:

      • content: It is required parameter. It specifies the new text content for the selected elements containing the HTML tags.
      • function(index, curContent): It is optional parameter. It specifies the function that returns the new content for the selected elements.
      • index: It returns the index position of element in the set.
      • curContent: It returns the current HTML content of selected elements.

    Example 1: This example changes the content by using JQuery’s text() method .

    <!DOCTYPE HTML> 

    <html

        <head

            <title

                JQuery | Change the text of a span element

            </title>

            <script src

            </script>

        </head

        <body style = "text-align:center;" id = "body"

            <h1 style = "color:green;"

                GeeksForGeeks 

            </h1

            <span id="GFG_Span" style = "font-size: 15px; font-weight: bold;"

                This is text of Span element. 

            </span>

            <br><br>

            <button

                Change

            </button>

            <p id = "GFG_DOWN" style

                "color:green; font-size: 20px; font-weight: bold;">

            </p>

            <script>

                $('button').on('click', function() {

                    $('#GFG_Span').text("New Span text content");

                    $('#GFG_DOWN').text("Span content changed");

                });     

            </script

        </body

    </html>                    

    Output:

    Example 2: This example changes the content by using JQuery’s html() method .

    <!DOCTYPE HTML> 

    <html

        <head

            <title

                JQuery | Change the text of a span element

            </title>

            <script src

            </script>

        </head

        <body style = "text-align:center;" id = "body"

            <h1 style = "color:green;"

                GeeksForGeeks 

            </h1

            <span id="GFG_Span" style = "font-size: 15px; font-weight: bold;">

                 This is text of Span element. 

            </span>

            <br><br>

            <button

                Change

            </button>

            <p id = "GFG_DOWN" style

                "color:green; font-size: 20px; font-weight: bold;">

            </p>

            <script>

                $('button').on('click', function() {

                    $('#GFG_Span').html("<p>New Span text content</p>");

                    $('#GFG_DOWN').text("Span content changed");

                });     

            </script

        </body

    </html>                    

    Output:

    To change text in a span using jQuery, the simplest way is to use the jQuery text() method:

    $("#div1 span").text("Changed Text");

    If your span will contain html content, then you should use the jQuery html() method.

    $("#div1 span").html("Changed <strong>Text</strong>");

    Let’s say I have the following HTML:

    <div id="div1">
      <p>Today is <span>November</span> 3rd.</p>
    </div>
    

    If I want to change the text inside the span from “November” to “December”, I can use the jQuery text() method to do this with the following Javascript code.

    $("#div1 span").text("December");

    If you are using WordPress, don’t forget to change the $ to jQuery as below:

    jQuery("#div1 span").text("December");

    We can also use the jQuery html() method to change the content of a span.

    $("#div1 span").html("December");

    While the text() method is very simple, the html() method gives us the ability to insert html into our span, which gives us more options when styling the content.

    Changing the Text in a Span Using jQuery with a Click

    Many times when creating a web page and the user experience, we want to change the content of a span after an interaction with another element on the web page.

    To change the text of a span using jQuery, we can combine the text() method with a click event.

    Let’s say I have the following HTML, and I want to give the user the ability to change the text of the span from “November” to “December”.

    <div id="div1">
      <div id="click-me">Click here to update span.</div>
      <p>Today is <span>November</span> 3rd.</p>
    </div>
    

    We can utilize both the jQuery click() method and jQuery text() method to change the text from “November” to “December”.

    Below is the Javascript code which will allow the user to be able to update the text in the span:

    $("#click-me").click(function(){
        $("#div1 span").text("December");
    }); 

    The final code and output for this example of how to change the text of a span using the jQuery text() method and Javascript is below:

    Code Output:

    Click here to update span.

    Today is November 3rd.

    Full Code:

    <div class="html-code-output">
    <div id="div1">
      <div id="click-me">Click here to update span.</div>
      <p>Today is <span>November</span> 3rd.</p>
    </div>
    </div>
    
    <script>
    
    $("#click-me").click(function(){
        $("#div1 span").text("December");
    });
    
    </script>
    

    Using the html() Method to Change Text in Span

    The jQuery html() method is very useful when it comes to manipulating web pages.

    We can use the jQuery html() method to change the html and text of a span.

    Let’s say we have the following code and we want to give the user the ability to add html content to the span.

    <div id="div1">
      <div id="click-me">Click here to update span.</div>
      <p>We are going to add html to this <span>span with content</span>.</p>
    </div>
    

    If we want to make the text “content” bold, we can do this easily utilizing both the jQuery click() method and jQuery html() method.

    Below is the Javascript code which will allow the user to be change the content in the span.

    $("#click-me").click(function(){
        $("#div1 span").html("span with <strong>content</strong>");
    });

    The final code and output for this example of how to change text of a span using the jQuery html() method and Javascript is below:

    Code Output:

    Click here to update span.

    We are going to add html to this span with content.

    Full Code:

    <div class="html-code-output">
    <div id="div1">
      <div id="click-me">Click here to update span.</div>
      <p>We are going to add html to this <span>span with content</span>.</p>
    </div>
    </div>
    
    <script>
    
    $("#click-me").click(function(){
        $("#div1 span").html("span with <strong>content</strong>");
    });
    
    </script>
    

    Hopefully this article has been useful for you to understand how to change text in a span using jQuery.

    29.12.2019Веб-технологии, Веб-технологии Вопросы

    При наличии HTML-документа задача состоит в том, чтобы изменить текстовое содержимое элемента <span>. Существуют различные методы изменения элементов span, которые обсуждаются ниже:

    • jQuery text () Метод: Этот метод устанавливает / возвращает текстовое содержимое указанных элементов. Если этот метод используется для возврата содержимого, он возвращает текстовое содержимое всех соответствующих элементов (теги HTML будут удалены). Если этот метод используется для установки содержимого, он перезаписывает содержимое всех соответствующих элементов.

      Синтаксис:

      • Возвращает текстовое содержание.
        $(selector).text()
      • Устанавливает текстовое содержание.
        $(selector).text(content)
      • Установите текстовое содержимое с помощью функции.
        $(selector).text(function(index, curContent))

      Параметры:

      • content: Обязательный параметр. Он определяет новый текстовый контент для выбранных элементов.
      • функция (index, curContent): это необязательный параметр. Он определяет функцию, которая возвращает новое текстовое содержимое для выбранных элементов.
      • index: Возвращает позицию индекса элемента в наборе.
      • curContent: возвращает текущее содержимое выбранных элементов.
    • jQuery html () Метод: Этот метод устанавливает / возвращает содержимое (HTML) указанных элементов. Если этот метод используется для возврата содержимого, он возвращает содержимое первого соответствующего элемента. Если этот метод используется для установки содержимого, он перезаписывает содержимое всех соответствующих элементов.

      Синтаксис:

      • Вернуться содержание
        $(selector).html()
        
      • Установить содержание
        $(selector).html(content)
        
      • Установить контент с помощью функции
        $(selector).html(function(index, curContent))
        

      Параметры:

      • content: Обязательный параметр. Он определяет новое текстовое содержимое для выбранных элементов, содержащих теги HTML.
      • функция (index, curContent): это необязательный параметр. Он определяет функцию, которая возвращает новое содержимое для выбранных элементов.
      • index: Возвращает позицию индекса элемента в наборе.
      • curContent: возвращает текущее HTML-содержимое выбранных элементов.

    Пример 1. Этот пример изменяет содержимое с помощью метода text () JQuery .

    <!DOCTYPE HTML> 

    <html

        <head

            <title

                JQuery | Change the text of a span element

            </title>

            <script src

    "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">

            </script>

        </head

        <body style = "text-align:center;" id = "body"

            <h1 style = "color:green;"

                GeeksForGeeks 

            </h1

            <span id="GFG_Span" style = "font-size: 15px; font-weight: bold;"

                This is text of Span element. 

            </span>

            <br><br>

            <button

                Change

            </button>

            <p id = "GFG_DOWN" style

                "color:green; font-size: 20px; font-weight: bold;">

            </p>

            <script>

                $('button').on('click', function() {

                    $('#GFG_Span').text("New Span text content");

                    $('#GFG_DOWN').text("Span content changed");

                });     

            </script

        </body

    </html>                    

    Выход:

    Пример 2. Этот пример изменяет содержимое с помощью метода JQuery html () .

    <!DOCTYPE HTML> 

    <html

        <head

            <title

                JQuery | Change the text of a span element

            </title>

            <script src

    "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">

            </script>

        </head

        <body style = "text-align:center;" id = "body"

            <h1 style = "color:green;"

                GeeksForGeeks 

            </h1

            <span id="GFG_Span" style = "font-size: 15px; font-weight: bold;">

                 This is text of Span element. 

            </span>

            <br><br>

            <button

                Change

            </button>

            <p id = "GFG_DOWN" style

                "color:green; font-size: 20px; font-weight: bold;">

            </p>

            <script>

                $('button').on('click', function() {

                    $('#GFG_Span').html("<p>New Span text content</p>");

                    $('#GFG_DOWN').text("Span content changed");

                });     

            </script

        </body

    </html>                    

    Выход:

    Рекомендуемые посты:

    • JavaScript | Изменить текст элемента span
    • JQuery | Получить текст элемента span
    • JavaScript | Получить текст элемента span
    • Как изменить текст заполнителя с помощью jQuery?
    • Как изменить текст кнопки с помощью jQuery?
    • Как изменить идентификатор элемента с помощью jQuery?
    • Как изменить имя элемента HTML с помощью jQuery?
    • Как изменить атрибут src элемента img в JavaScript / jQuery?
    • Как изменить текст метки с помощью JavaScript?
    • Как показать элемент span для каждой строки, нажатой в AngularJS?
    • Как изменить значение флажка с помощью jQuery?
    • Как изменить фоновое изображение с помощью jQuery?
    • Как изменить стиль курсора с помощью jQuery?
    • JQuery | Метод text ()
    • JQuery | : селектор текста

    JQuery | Изменить текст элемента span

    0.00 (0%) 0 votes

    Учитывая документ HTML, и задача состоит в том, чтобы изменить текстовое содержимое элемента <span>. Существуют различные методы, используемые для изменения элементов диапазона, которые обсуждаются ниже:

    • Метод jQuery text (): этот метод устанавливает / возвращает текстовое содержимое указанных элементов. Если этот метод используется для возврата содержимого, он возвращает текстовое содержимое всех совпавших элементов (теги HTML будут удалены). Если этот метод используется для установки содержимого, он перезаписывает содержимое всех совпадающих элементов.

      Синтаксис:

      • Он возвращает текстовое содержимое.
         $ (селектор) .text ()
      • Устанавливает текстовое содержимое.
         $ (селектор) .text (контент)
      • Установите текстовое содержимое с помощью функции.
         $ (селектор) .text (функция (индекс, curContent))

      Параметры:

      • содержание: обязательный параметр. Он определяет новое текстовое содержимое для выбранных элементов.
      • function (index, curContent): необязательный параметр. Он определяет функцию, которая возвращает новое текстовое содержимое для выбранных элементов.
      • index: возвращает позицию индекса элемента в наборе.
      • curContent: возвращает текущее содержимое выбранных элементов.
    • Метод jQuery html (): этот метод устанавливает / возвращает содержимое (HTML) указанных элементов. Если этот метод используется для возврата содержимого, он возвращает содержимое первого совпадающего элемента. Если этот метод используется для установки содержимого, он перезаписывает содержимое всех совпадающих элементов.

      Синтаксис:

      • Вернуть контент
        $ (селектор) .html ()
        
      • Установить контент
        $ (селектор) .html (контент)
        
      • Установить контент с помощью функции
        $ (селектор) .html (функция (индекс, curContent))
        

      Параметры:

      • содержание: обязательный параметр. Он определяет новое текстовое содержимое для выбранных элементов, содержащих теги HTML.
      • function (index, curContent): необязательный параметр. Он определяет функцию, которая возвращает новое содержимое для выбранных элементов.
      • index: возвращает позицию индекса элемента в наборе.
      • curContent: возвращает текущее HTML-содержимое выбранных элементов.

    Пример 1. В этом примере содержимое изменяется с помощью метода JQuery text () .

    <!DOCTYPE HTML>

    < html >

    < head >

    < title >

    JQuery | Change the text of a span element

    </ title >

    < script src =

    </ script >

    </ head >

    < body style = "text-align:center;" id = "body" >

    < h1 style = "color:green;" >

    GeeksForGeeks

    </ h1 >

    < span id = "GFG_Span" style = "font-size: 15px; font-weight: bold;" >

    This is text of Span element.

    </ span >

    < br >< br >

    < button >

    Change

    </ button >

    < p id = "GFG_DOWN" style =

    "color:green; font-size: 20px; font-weight: bold;" >

    </ p >

    < script >

    $('button').on('click', function() {

    $('#GFG_Span').text("New Span text content");

    $('#GFG_DOWN').text("Span content changed");

    });

    </ script >

    </ body >

    </ html >

    Выход:

    Пример 2: В этом примере содержимое изменяется с помощью метода JQuery html () .

    <!DOCTYPE HTML>

    < html >

    < head >

    < title >

    JQuery | Change the text of a span element

    </ title >

    < script src =

    </ script >

    </ head >

    < body style = "text-align:center;" id = "body" >

    < h1 style = "color:green;" >

    GeeksForGeeks

    </ h1 >

    < span id = "GFG_Span" style = "font-size: 15px; font-weight: bold;" >

    This is text of Span element.

    </ span >

    < br >< br >

    < button >

    Change

    </ button >

    < p id = "GFG_DOWN" style =

    "color:green; font-size: 20px; font-weight: bold;" >

    </ p >

    < script >

    $('button').on('click', function() {

    $('#GFG_Span').html("< p >New Span text content</ p >");

    $('#GFG_DOWN').text("Span content changed");

    });

    </ script >

    </ body >

    </ html >

    Выход:

    jQuery change content of div span; In this tutorial, you will learn how to change or replace div, span , button, paragraph text, or content in html using jQuery html() method.

    jQuery Html Method

    The jQuery html () method is used to change the entire contents of the selected elements. This selected element replaces content with new content.

    Syntax jQuery Html Method

    $(selector).html()  

    html() method returns the content of first matched element.

    $(selector).html(content)  

    Html() method sets the content of matched element.

    $(selector).html(function (index, currentcontent))  

    It sets the content using function.

    The HTML () method is used either to set content or to return the contents of the selected elements.

    • To set the content :- When you use this method to set the content, it overwrites the contents of all matched elements.
    • To return the content :- When you use this method to return content, it first returns the content of the matched element.

    Parameters of jQuery Html Method

    Parameter Description
    Content It is an essential parameter. It is used to specify the new content for the selected elements. It can also contain HTML tags.
    Function (index, currentcontent) It is an optional parameter. It specifies a function that returns the new content for the selected elements.Index: It shows the index position of the element in the set.Currentcontent: It shows the current HTML content of the selected element.

    Ex 1 :- jQuery html() method

    Let’s see an example 1 of html() method.

    <!DOCTYPE html>  
    <html>  
    <title>Learn Jquery Html Method</title>
    <head>  
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>   
    <script>  
    $(document).ready(function(){  
        $("#btn_click").click(function(){  
            $("#para").html("Hello <b>there, Thanks to try it</b>");  
        });  
    });  
    </script>  
    </head>  
    <body>  
    <button id="btn_click">Click here to change the content</button>  
    <p id="para">This is a paragraph. When you click the button after that it will change.</p>  
    </body>  
    </html>  
    

    Ex 2 :- jQuery html()

    Let’s see example2 of html method. This example returns the first match of element.

    <!DOCTYPE html> 
    <html> 
    <head> 
    <title> jQuery html() Method </title> 		
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>   
    </head> 
    	
    <body style = "text-align:center;"> 
    			
      <h1 style = "color:blue;" >Hello World </h1> 
      <h2>jQuery | html() Method </h2> 
    	
      <button id="btn-click">Click</button> 
    	<script> 
    		$(document).ready(function(){ 
    			$("#btn-click").click(function(){ 
    				alert($("h2").html()); 
    			}); 
    		}); 
    	</script> 
    </body> 
    </html> 
    
    

    Ex 3 :- jQuery replace text

    Let’s take a new example using the jQuery html() method. It will replace the h2 tag text. See the example below

    <!DOCTYPE html> 
    <html> 
    <head> 
    <title> jQuery replace text using html() </title>        
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>   
    </head> 
        
    <body style = "text-align:center;"> 
                
      <h1 style = "color:blue;" >Hello World </h1> 
      <h2>jQuery | html() Method </h2> 
        
      <button id="btn-click">Click</button> 
        <script> 
            $(document).ready(function(){ 
                $("#btn-click").click(function(){ 
                    $("h2").html('Hello'); 
                }); 
            }); 
        </script> 
    </body> 
    </html> 
    
    

    Recommended jQuery Tutorial

    1. jQuery Text Method By Example
    2. Get and Set Input, Select box, Text, radio Value jQuery
    3. Duplicate Html Elements Using jQuery By Example
    4. jQuery | Event MouseUp By Example
    5. Event jQuery Mouseleave By Example
    6. jQuery Event Mouseenter Example
    7. Event jQuery MouseOver & MouseOut By Example
    8. keyup jquery event example
    9. Jquery Click Event Method with E.g.
    10. Event jQuery. Blur By Example
    11. jQuery form submit event with example
    12. keydown function jQuery
    13. List of jQuery Events Handling Methods with examples
    14. Jquery Selector by .class | name | #id | Elements
    15. How to Get the Current Page URL in jQuery
    16. jQuery Ajax Get() Method Example
    17. get radio button checked value jquery by id, name, class
    18. jQuery Set & Get innerWidth & innerHeight Of Html Elements
    19. jQuery Get Data Text, Id, Attribute Value By Example
    20. Set data attribute value jquery
    21. select multiple class in jquery
    22. How to Remove Attribute Of Html Elements In jQuery
    23. How to Checked Unchecked Checkbox Using jQuery
    24. jQuery removeClass & addClass On Button Click By E.g.
    25. To Remove whitespace From String using jQuery
    26. jQuery Ajax Post Method Example
    27. jQuery Ajax Get Method Example
    28. To Load/Render html Page in div Using jQuery Ajax $.load
    29. jQuery Sibling Methods – To Find Siblings Elements
    30. jQuery Find Siblings Elements with Class, id

    My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

    View all posts by Admin

    Понравилась статья? Поделить с друзьями:
  • Jquery как изменить value input
  • Jquery как изменить src картинки
  • Jquery как изменить css свойства
  • Jquery вывод ошибки
  • Jquery validation error class