Skip to content

Instantly share code, notes, and snippets.

@zgulde
Last active February 17, 2016 19:20
Show Gist options
  • Save zgulde/847c74ae17f05958aae5 to your computer and use it in GitHub Desktop.
Save zgulde/847c74ae17f05958aae5 to your computer and use it in GitHub Desktop.

4.1 jQuery Selectors

The awesomeness of jQuery comes from it's ability to let us use CSS selectors to manipulate the DOM. Almost and CSS selector you had previously used for styling you can use to grab HTML elements with jQuery.

We can use jQuery to manipulate multiple elements at the same time. For example:

HTML

<p class="para">lorem ipsum</p>
<p class="para">lorem ipsum</p>
<p class="para">lorem ipsum</p>

JS

$('.para').css('color', 'firebrick');

This change to font color of all the paragraphs to a nice shade of red.


Will this code change the color of all the paragraphs? Why or why not?

HTML

<p id="para">lorem ipsum</p>
<p id="para">lorem ipsum</p>
<p id="para">lorem ipsum</p>

JS

$('#para').css('color', 'firebrick');

4.2 Click events and this

MDN Refrence

What will be displayed in the console?

HTML

<p>lorem ipsum</p>

JS

$('p').click(function(){
    console.log(this);
});

What will be displayed in the console?

JS

var myObject = {
    myProperty: 'codeup',
  
    logThis: function(){
        console.log(this);
    }
};

myObject.logThis();

What will be displayed in the console when the h1 is clicked on?

HTML

<h1>hello, world!</h1>

JS

var myObject = {
    myProperty: 'codeup',
  
    addListenerToH1: function(){
      $('h1').click(function(){
          console.log(this);
      });
    }
};

myObject.addListenerToH1();

Bonus Points

What will be displayed in the console when the second li is clicked?

HTML

<ul>
  <li>one</li>
  <li id="list-item-two">two</li>
  <li>three</li>
</ul>

JS

$('#list-item-two').click(function(){
    setTimeout(function(){
        console.log(this);
    }, 300);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment