.text()
.text() Method
- Method is either used to get (read) the combined text contents of the selected elements, including their descendants, or set (write) the text contents of the selected elements
Example of Getting (Reading) text
- To Get (Read) text of an element use
.text()
with nothing inside the parentheses
$(() => {
$('#readAll').click(() => {
// read text from all p elements
const allParagraphs = $("p").text()
alert(`text from all paragraphs: ${allParagraphs}`)
})
$('#readFirst').click(() => {
// read text from only the 1st p element
const firstParagraph = $("p:first").text()
alert(`text from the 1st paragraph: ${firstParagraph}`)
})
})
JS Bin on jsbin.com
Example of Setting (writing) text
- To Set (Write) text of an element use
.text(newText)
with the new text inside the parentheses
$('#convertAllWords').click(() => {
// set text for all p elements to spanish translation
$(".one").text("uno")
$(".two").text("dos")
$(".three").text("tres")
})
JS Bin on jsbin.com