Blog

Filter posts by Category Or Tag of the Blog section!

Selectors in Jquery

Monday, 18 February 2013

Selectors in jQuery are used to select and manipulate HTML elements on a web page. Selectors are written using CSS syntax, and they allow you to target specific elements on the page based on their tag name, class, ID, or other attributes. Here are some commonly used selectors in jQuery:

 

  1. Tag Selector: Targets all elements with the specified tag name, for example, $('p') targets all paragraphs.

 

$('h2').css('font-size', '24px');


 

  1. Class Selector: Targets all elements with the specified class name, for example, $('.my-class') targets all elements with the class my-class.

 

$('.highlight').css('background-color', 'yellow');


 

  1. ID Selector: Targets the element with the specified ID, for example, $('#my-id') targets the element with the ID my-id. 

 

$('#myElement').hide();

 

  1. Attribute Selector: Targets all elements that have the specified attribute, for example, $('[href]') targets all elements that have the href attribute.

 

$('input[type="text"]').prop('disabled', true);


 

  1. Descendant Selector: Targets elements that are descendants of a specified parent element, for example, $('ul li') targets all li elements that are descendants of ul elements.

 

     

$('ul li').css('font-weight', 'bold');


 

  1. Child Selector: Targets direct children of a specified parent element, for example, $('ul > li') targets all li elements that are direct children of ul elements.

 

$('ul > li').css('color', 'blue');


 

  1. :first Selector: Targets the first element that matches the selector, for example, $('li:first') targets the first li element.

 

$('p:first').css('color', 'green');



 

These are just a few examples of selectors available in jQuery. By using different combinations of these selectors, you can target and manipulate specific elements on a web page to achieve the desired effect

 

comments powered by Disqus