Main functions in jQuery to add remove web content and get HTML values


Published on 14 February 2023


Main functions in jQuery to add remove web content and get HTML values

Basic jQuery functions to modify a web page structure

Within a web page sometimes we want to modify its structure, not its styles, that is, modify the DOM by adding, deleting or changing its elements.
jQuery provides us with many functions that can be useful to modify the structure of a web page, such as empty(), html(), text(), append(), prepend(), appendTo() , prependTo(), wrap(), unwrap(), wrapAll(), wrapInner() and val(). 

Understanding the DOM

The World Wide Web is a network of interconnected web pages. Each web page is a document, and the most common web page is HTML stands for Hyper Text Markup Language. A markup language is language that tells a computer how to generate content. HTML is the markup language used to create web pages. The term DOM refers to the Document object model.

The World Wide Web was first introduced in 1989 with the release of Tim Berners Lee's proposal for the World Wide Web. Although it was initially developed with CERN in mind, the Internet has now become the main source of information and communication for almost everyone on earth. Both public and private organizations use the internet to communicate and share data with each other. The internet is also used by individuals to access the information they want and need. The main components of a web page are HTML, CSS, and JS; these are known as the Document object model, Style sheet, and JavaScript, respectively. Together, these components make up what is known as the DOM in html.

Html is a computer language used to create websites. Each webpage is an html document and consists of various elements such as html forms, html links, and text boxes where people can type in their information. HTML documents contain content, structure, and style. An html document is made up of various html tags- elements that make up an html page. There are many different types of html tags, including  for the body of the webpage,  for heading level 1,  for paragraph and  links to other websites etc.

The DOM in html refers to the Document object model. All web browsers have this feature so that they can interact with web pages through scripts written in JavaScript. A web browser is what allows people to access the internet- it's a computer program that allows you to view web pages. All internet connections use sockets or tcpip to send data to and receive data from different other computers on the network. Browsers interact with web pages through scripts written in DOM by making calls to different functions on different objects within the page tree- these objects are known as nodes within the DOM tree.

Web pages are created using html markup tags such as  for heading level 1 or  for paragraph. Each webpage has an introductory heading consisting of one level 1 heading followed by subsequent headings at higher levels. Paragraphs consist of one or more lines of text separated by newlines or spaces directed towards specific objectives such as creating easy-to-read content or creating visually engaging presentations or advertisements. HTML is then converted into a machine language by a web browser so that it can be viewed through a screen onto a monitor or projected onto a television using an HDMI cable connection between a computer monitor or television screen and an HDCP compatible projector or video monitor.

jQuery empty() function

The .empty() function deletes all child nodes and their contents from the selected elements.

In the following example we have a list with id list and a button with id del. When we click on the button we create a function that selects the list and deletes its content with the empty() function.

<script>
  $('#del').click(function(){
    $('ul#list').empty();
  });
</script>

Try it Yourself

html() function in jQuery

The .html() function is used to get all the html content of the first element of all the selected ones. We can also modify the content of all the selected elements or add html content inside that selected element.

In the following web example we have a list with id list, two buttons to copy and replace and a div with id show.

  • We select the button with id copy, when clicked we get the html content of the list, then we select the div with id show and add that html content.
  • We select the button with id replace, when clicking we generate a function that selects the list and replaces the old html content with a new one.

<script>
  $('#copy').click(function(){
    var content_html = $('ul#list').html();
    $('#show').html(content_html);
  });
  $('#replace').click(function(){
    $('ul#list').html(function(index,oldText){
      return '<li>New Text '+index+'</li>';
    });
  });
</script>

Try it Yourself

text() function in jQuery

The text() function obtains the content in text mode of the first element of the selected ones, ignoring the existing html tags.

In the following web:

  • By means of a variable text we store the text with the function text in the first div and we also show it with the function text in the second div with id show.
  • We see how the function text only saves the information of the text and not the html content that may have.

<script>
  var text = $('div#first_div').text();
  $('#show').text(text);
</script>

Try it Yourself

append() function in jQuery

The append() function adds html content right at the beginning of the selected elements.

In the following web we have two ul lists that we will manipulate with the append function: :

  • Select each li in the list with id list and add a new li after each li.
  • Select the list with id list and add a new li to it
  • Select each li in the list with id list2 and add a new li with text and index after each li.

<script>
  $('ul#list li').append('<li>Text after li</li>');
  $('ul#list').append('<li>Text 5</li>');
  $('ul#list2 li').append(function(index){
    return '<li>Text with index value '+index+'</li>';
  });
</script>

Try it Yourself

prepend() method in jQuery

prepend() function adds html content right at the end of the selected elements.

In the following web  we have two ul lists that we will manipulate with the prepend function: 

  • Select each li in the list with id list and add a new li before each li
  • Select the list with id list and add a new li to it
  • Select each li in the list with id list2 and add a new li with text and index before each li

<script>
  $('ul#list li').prepend('<li>Text before li</li>');
  $('ul#list').prepend('<li>Text 5</li>');
  $('ul#list2 li').prepend(function(index){
    return '<li>Text prepend with index value '+index+'</li>';
  });
</script>

Try it Yourself

appendTo() and prependTo() functions in jQuery

appendTo() and prependTo() work in much the same way as the append() and prepend() functions. The difference is, where before was the content now is the selector of the elements in which we are going to add content.

  • appendTo() adds content right at the beginning of the selected elements.
  • prependTo() adds content right at the end of the selected elements.

The following web example we have a div with id list. The scripts executed, using the appendTo() and prependTo() functions, will be the following:

  • We select the following html code "<p id="par">Text 1</p>" and attach it inside the final part of the div with id list.
  • We select the following html code "<div id="inner">New Content</div>" and attach it inside the final part of the div with the id par recently created in the previous step.
  • We select the following html code "<div id="new">Pre Content</div>" and attach it inside the initial part of the div with id inner just created in the previous step.

<script>
  $('<p id="par">Text 1</p>').appendTo('#list');
  $('<div id="inner">New Content</div>').appendTo('#par');
  $('<div id="new">Pre Content</div>').prependTo('#inner');
</script>

Try it Yourself

wrap() function in jQuery

The .wrap() function adds HTML structure around each and every selected element.

The following web example, we have a div with id article. The scripts executed, using the wrap() function, will be the following:

  • We select the div with id "article" and place it inside the div with id article_external.
  • Select the div with id "article" and place it inside the div with id article_ and the index of the generated function. This div in turn must be inside the div with id article_external.

<script>
  $("#article").wrap('<div class="article_external">External Content</div>');
  $('#article').wrap(function(ind){
    return '<div id="article_"'+ind+'">Article '+ind+'</div>';
  }); </script>

Try it Yourself

unwrap(), wrapInner() and wrapAll() functions in jQuery

  • Function .unwrap() is the opposite of wrap(), it removes the html element that wraps the inner element.

Example:

$("#article").unwrap();

  • wrapAll() is almost the same as the wrap() function. It just adds a wrapper element that covers all the selected elements.
  • wrapInner() is almost the same as the wrap() function, but the wrapping element is added inside the content of the selected elements.

The following web example, we have 3 divs with id content each. The scripts executed, using the wrapAll() and wrapInner() functions, will be the following:

  • We select all the div with id content and place a div with id content_external that wraps them all.
  • We select all the div with id content and we place in its interior a div with id content_inner that is wrapped by each selected div.

<script>
  $("div#content").wrapAll('<div class="content_external">External Content</div>');
  $('div#content').wrapInner('<div class="content_inner">Inner Content </div>');
</script>

Try it Yourself

val() function in  jQuery

The val() function allows to obtain and set the value of the different fields of a form.

Example 1 val() function

The following web example, we have a div with id content and an input with id log. The scripts executed, using the val() function, will be the following:

  • Store in the variable my_value the value of the input text with id log.
  • Select the div with id content and I set as html content the value of the variable my_value.
  • Select the input text with id log and I add the value "Insert Value".

<div id="content"></div>
<input type="text" name="log" value="Your Login" id="log">

<script>
  var my_value = $("input[type=text]#log").val();
  $('#content').html(my_value);
  $("input[type=text]#log").val("Insert Value");
</script>

Try it Yourself

Example 2 val() function

In the following web example we have a selector with 3 color options and 3 checkboxes with different car models of which one is marked:

  • We store in a variable "colorValue" the value of the selected color.
  • We select the class "car" and of each one we create a function that shows us by console its value.
  • We select all the "input name=car" and of each one we create a function that shows us by console its value.
  • We select all the "input name=car" and from each one we create a function that shows us its value in case it is checked.

<select id="color">
  <option>Blue</option>
  <option>White</option>
  <option>Black</option>
</select>
<input type="checkbox" name="car" class="car" value="BMW" checked> BMW
<input type="checkbox" name="car" class="car" value="Ford"> Ford
<input type="checkbox" name="car" class="car" value="Mercedes"> Mercedes
<script>
  var colorValue = $( "#color" ).val();
  console.log('Color Selected: '+colorValue);
  $('.car').each(function(){
    console.log('CARS: '+$(this).val());
  });
  $('input[name=car]').each(function(){
    console.log('CARS Again: '+$(this).val());
  });
  $('input[name=car]').each(function(){
    if ($(this).is(":checked")) {
      console.log('Car Checked: '+$(this).val());
    }
  });
</script>

Try it Yourself


Tips on SEO and Online Business

Next Articles

Previous Articles