Skip to content

Editing HTML and CSS

With jQuery you can easily manipulate HTML and CSS. You can change the content of any element, add a piece of html code in the place we choose , copy elements and freely manipulate objects on the site.

Text() method

  • returns text content from all matched selectors:
$(selector).text(); 
  • sets the text in all matched selectors:
$(selector).text('text');

An example:

$('p').text('Hello world!'); 

It will set the text Hello world! in all <p> tags.

html() method

  • returns content from the first matched selector:
$(selector).html(); 
  • sets the HTML code in all matched selectors:
$(selector).html('htmlCode');

Example

$('p').html('Hello <b>world</b>!'); 

Methods for adding new content

  • append() - inserts content at the end of the selected selector.
  • prepend() - inserts content at the beginning of the selected selector.
  • after() - inserts content after the selected selector.
  • before() - inserts content before the selected selector.

Example

$('p.green').append('Hello world!'); 

Methods to remove content and elements

  • remove() - Deletes the selected element and the elements inside that element.
  • empty() - removes elements inside the selected element.

Example

$('p').empty();

The css() method

  • returns a specific CSS property from the first matched selector
$(selector).css('cssProperty'); 
  • sets the CSS property in all matched selectors
$(selector).css('cssProperty', 'value');

Example

$('p').css('color'); // will return the text color of first p element

$('p').css('color', 'red'); // will set the text color of all p elements

The val()method

  • returns a value from the first matched field of the form:
$(selector).val(); 
  • sets the value to all matched form fields:
$(selector).val('text');

Example

$('input#name').val();

$('input#email').val('name@gmail.com');

Methods to add and remove classes

  • addClass() - adds one or more classes to the selected element.
  • removeClass() - removes one or more classes from the selected element.

Example

$('div').addClass('important');

$('p').removeClass('green', 'important');