jQuery Selector fundametals

jQuery Selector :-  jQuery selector work as a CSS selector . CSS selector is used to add style to the HTML Page while jQuery selector is used to add behaviors to the HTML Page. 

Selecting Elements by JavaScript

Selecting Elements by jQuery

document.getElementsByTagName(“p”)[0].innerHTML = “Change the page.”; $(“p”).html(“Change the page.”);
for (i = 0; i <= 4; i++){document.getElementsByTagName(“p”)[i].innerHTML=”Change the page”;

}

$(“p”).html(“Change the page.”);

What is “$” sign means in jQuery?

“$” is not other than “jQuery”. It is symbolic notation of “jQuery” word. 

CSS Selector

jQuery Selector

h1 {text-align: left ;} – Selection by Element. $(“h1”).append () – Selection by Element.
.my_class{position: absolute;} – By Class $(“.my_class”).append() – By Class
#my_id {color: #3300FF;} – By ID $(“#my_id”).append() – By ID

 Example:-

  1. $(“div”).remove () – This will give all the div on the page.
  2. $(“#Id_name”) .remove () – This will give the DOM element having id mentioned.
  3. $(“.class_name”) .remove () – This will give the entire DOM element using class mentioned.
  4. $(“div.class_name”) .remove () – This will give all the div using this class on the page.
  5. $(“div div img”) .remove () – This will select the images under div which is in another div.

 Special Selector

$(this) .remove () – It will select the current element “Current Element”. It’s meaning change throughout the code.

Difference between .html() and .text() functions in jQuery

Difference between .html() and .text() functions in jquery:

.html() can be used to get the contents of inside an element. If your selector expression matches more than one element, only the first match will have its HTML content returned:

here is an example:

  • list sample 1
  • list sample 2
  • list sample 3

now if you are using .html():
$(‘.html-function-demo’).html();

your output is:

  • list sample 1
  • list sample 2
  • list sample 3

now if you are using .text():
$(‘.html-function-demo’).text();

your output is:
list sample 1 list sample 2 list sample 3

due to different properties of HTML Parsers of your browser, the output for your function varies in the manner that the output will be in one line or continuous one or with spaces and linebreaks.

Both functions return strings as their output.

Changing The Value Of a Div on Click of a Button From a Set of Radio Button Using jQuery

Changing the value of a div on click of a button from a set of radio button using jquery:
<div>
<ul>
<li><input type=”radio” value=”radio1″ name=”demoChangeFunc” /></li>
<li><input type=”radio” value=”radio2″ name=”demoChangeFunc” /></li>
<li><input type=”radio” value=”radio3″ name=”demoChangeFunc” /></li>
<li><input type=”radio” value=”radio4″ name=”demoChangeFunc” /></li>
</ul>
<div></div>
</div>

$(‘.radio-button-demo input’).each(function() {
if($(this).attr(‘checked’,’checked’)){
$(‘.list-value’).text($(this).attr(‘value’));
}
})

1 2