Sunday, May 14, 2017

jQuery allows you to modify multiples elements in one go, you can modify attributes, text, or color of multiple HTML elements by executing just one line of jQuery code. In this jQuery tutorial, I will show you how to modify multiple <li> elements in one go. In our example, we have a couple of <li> tag to display sub-headings, now we will change them in one go using jQuery. If you look at our HTML, we have an ordered list <ol> to display top 10 programming languages, each of them is a <li> item. We also have one button, "Click Me", which will when clicked, changes all <li> item's text to "jQuery is the new Boss". Here is the jQuery code, which does that.

As usual, the code is written inside the document.ready() function. In the first line, we have attached an event handler with button, selected using id selector. When a button with id "btn" will click, jQuery will find all <li> tags by using tag jQuery tag selector$('li') and then changes their text.

jQuery Example to Modify Multiple DOM elements in one click

Here is complete HTML + jQuery code for your practice, you can either write it down to an HTML file or just copy paste to quickly run on a browser

How to run and test this jQuery program?

You can just copy and paste this HTML code into a text file and save it as HTML e.g. jquerydemo.html. After that, just open that file in a browser e.g. Google Chrome, Mozilla FireFox, or Microsoft's Edge browser. If you are a Java Developer you can also use Eclipse IDE's built-in web browser.

When you open the HTML file in a web browser it will look like below:

You can see that we have a list of 10 elements and now when you click the button, jQuery code will run because it is bonded with click event fired when you click the button. The jQuery will then use the tag selector$("li") to grab all list elements and changes its text as "jQuery is the new boss" by calling the text() method.

This way, you can change the multiple HTML elements in one go using jQuery. All that power comes from the CSS-like selector, the tag selector here. The web page will look like following after this change:

That's all on this part of jQuery beginners tutorials and tips. As usual, a task only required a couple of line of jQuery code, rather than 10 lines of raw JavaScript code. We have seen how to modify multiple elements in one go, you can select multiple elements using jQuery tag selector, which takes a tag and select all elements. You can read jQuery in Action to learn more about different types of selectors available in jQuery.