Skip to content

Instantly share code, notes, and snippets.

@whitschrader
Forked from OfTheDelmer/jQuery_intro.md
Created January 31, 2014 18:41
Show Gist options
  • Select an option

  • Save whitschrader/8739560 to your computer and use it in GitHub Desktop.

Select an option

Save whitschrader/8739560 to your computer and use it in GitHub Desktop.

Intro to jQuery

Dom Manipulation

Selectors in jQuery

In jQuery selecting elements is very similar to querySelectorAll that we covered with the js DOM api. To get a DOM element we use $('selector') to fetch the element from the DOM.

Let's do an #id example,

example_1

<div id="myDiv">
	Hello World!!
</div>

<script>
	$("#myDiv").css("color", "blue")
</script>

Or by css .myClass

example_2

<div class="myClass">
	Hello World!!
</div>

<div class="myClass">
	Hello World!!
</div>
	
<div class="myClass">
	Hello World!!
</div>
<script>
	$(".myClass").css("color", "blue")
</script>

With a random color

example_3

<div class="myClass">
	Hello World!!
</div>

<div class="myClass">
	Hello World!!
</div>
	
<div class="myClass">
	Hello World!!
</div>

<script>
  var randVal = function(){
    return Math.floor(Math.random()*255);
  };
  
  var randColor = function(){
    var red = randVal();
    var green = randVal();
    var blue = randVal();
    
    return "rgb("+red +","+green+","+blue+")";
  }
  $(".myClass").css("color", randColor())
</script>

Appending elements

Moving elements

example_4

 <style>
	#funList {
	  border: dashed 1px blue;
	  padding: 10px;
	}
	
</style>	

<div id="funList">
 
    <div id="funItem">
        Fun Stuff
    </div>
</div>

<script>
  var sampleData = {text: "Brooklyn Austin YOLO drinking vinegar authentic, fixie trust fund skateboard leggings fap mustache. Tote bag tattooed food truck DIY. Art party bespoke selvage narwhal four loko. High Life twee organic polaroid raw denim, Truffaut cred irony Pitchfork retro put a bird on it. Bushwick mlkshk yr viral Odd Future pour-over. Sartorial lomo organic whatever Portland. Disrupt deep v chia pug actually selfies, Pinterest mlkshk meh roof party."}
    
  var $sampleDiv = $("<div> " + sampleData["text"] + "</div>");
  
  $("#funList").append($sampleDiv);
   
</script>

example_5

<style>
	#funList {
	  border: dashed 1px blue;
	  padding: 10px;
	}
	
	#crazyList {
	  border: dashed 1px red;
	  padding: 10px;
	}
</style>	

<div id="funList">
 
    <div id="funItem">
        Fun Stuff
    </div>
</div>

<div id="crazyList">
  
</div>

<script>
	// Select `#funItem`
   var $funItem = $("#funItem");
   // Change color of `$funItem`
   $funItem.css("color", "red");
   
   //Move the $moveItem
   $("#crazyList").append($funItem);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment