Skip to content

Instantly share code, notes, and snippets.

@joel-oe-lacey
Last active December 13, 2019 18:47
Show Gist options
  • Save joel-oe-lacey/fb887f1324d09a6c82df9dd242bd701f to your computer and use it in GitHub Desktop.
Save joel-oe-lacey/fb887f1324d09a6c82df9dd242bd701f to your computer and use it in GitHub Desktop.
Get & Set Content in jQuery

How do you get the text from an element (like a paragraph) with jQuery??

If you just retrieve .text() on a selected element will grab selected text for you The .text() method cannot be used on input elements. For input field text, use the .val() method.

How do you set the text of an element (like a paragraph)?

You can also use .text to replace text, by passing the desired text in as an an argument

How do you get the text / content from an input?

.val() without arguments

How do you set the text / content of an input?

.val('new text') with an argument will replace the text content of input

How do you add / remove / toggle classes on an element?

.addClass() .removeClass() .toggleClass()

What’s the difference between .text() and .text([text])?

See above

If you select multiple elements with jQuery, do you have to use a for loop / iterate through each to modify their content? Give an example.

It will select all of the elements by default.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment