.text()

.text()

  • Allows you to either read (get) or write (set) the text of html elements (documentation)

Reading Text

  • To read (or get) the text of elements using jQuery you need to use the .text() method with nothing between the parentheses

// read the text found in the element .main
// notice how nothing is in-between the parentheses

$(".main").text();


Example #1 - Reading text using .text()

JS Bin on jsbin.com

In the example above jQuery is used to listen for a .click() event on the button element and then call the showMessage() function when the element is clicked

Inside the showMessage function, $("#lead") selects the element with an id of lead and uses the .text() method with nothing in-between the parentheses to READ text found in the #lead element

Writing Text

  • To write or update the text of elements using jQuery you need to use the .text() and place the new text in-between the parentheses

// Update the text found in .main to read "Hello World"
// notice how we place "Hello World" in-between the parentheses

$(".main").text("Hello World");


Example #2 - Writing text using .text()

JS Bin on jsbin.com

In the example above jQuery is used to listen for a .click() event on the button element and then call the changeLeadSinger() function when the element is clicked

Inside the changeLeadSinger function, $("#lead") selects the element with an id of lead and uses the .text(<new text>) method with the new text placed in-between the parentheses to WRITE new text to the #lead element