Skip to content

Instantly share code, notes, and snippets.

@jpweist
Created October 14, 2019 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpweist/af09026b884859f2a4ba698aa5d3f6f8 to your computer and use it in GitHub Desktop.
Save jpweist/af09026b884859f2a4ba698aa5d3f6f8 to your computer and use it in GitHub Desktop.
jQuery Getting and Setting Content
# Getting and Setting Content
For all applicable questions, compare and contrast using jQuery and vanilla JS.
- How do you get the text from an element (like a paragraph) with jQuery??
jQuery | text() Method .html
This method is used to set or return the text content of the element.
While setting the content, it overwrites the content of all the matched elements.
The returned content of text method() is used to return the text content of all matched elements.
- How do you set the text of an element (like a paragraph)?
.text()
- How do you get the text / content from an input?
JQuery val() method:
This method return/set the value attribute of selected elements.
If we use this method to return value, it will return the value of the FIRST selected element.
If we use this method to set value, it will set one or more than one value attribute for set of selected elements.
- How do you set the text / content of an input?
1, .html()By modifying elements for reading and HTML Tags
2, .text()To read or modify the text content elements
3, .val()To read or modify the form element of the value value
How do you add / remove / toggle classes on an element?
.addClass(), .removeClass(), .()toggleClass
- What’s the difference between .text() and .text([text])?
jQuery( ":text" )
$( ":text" ) allows us to select all <input type="text"> elements. As with other pseudo-class selectors
(those that begin with a ":") it is recommended to precede it with a tag name or some other selector;
otherwise, the universal selector ( "*" ) is implied. In other words, the bare $( ":text" )
is equivalent to $( "*:text" ), so $( "input:text" ) should be used instead.
Note: As of jQuery 1.5.2, :text selects input elements that have no specified type attribute
(in which case type="text" is implied).
This difference in behavior between $( ":text" ) and $( "[type=text]" ), can be seen below:
1
2
$( "<input>" ).is( "[type=text]" ); // false
$( "<input>" ).is( ":text" ); // true
- 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. no we can select them all at once and change them
$( "div, span, p.myClass" ).css( "border", "3px solid red" );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment