Skip to content

Instantly share code, notes, and snippets.

@MikeRogers0
Created June 16, 2012 17:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MikeRogers0/2941981 to your computer and use it in GitHub Desktop.
Save MikeRogers0/2941981 to your computer and use it in GitHub Desktop.
JavaScripts Selector Methods
<p id="myElem1" class="classExample">My First paragraph</p>
<p id="myElem2" class="classExample">My Second paragraph</p>
<script>
if(!document.querySelectorAll){ // If the user does not have querySelectorAll()
var classExample = document.getElementsByClassName('classExample'); // Get all the elements with class "classExample"
}else{ // Otherwise do it the HTML5 way
var classExample = document.querySelectorAll('.classExample');
}
for(i=0; i<classExample.length; i++) {// Cycle through them
classExample[i].style.fontSize = "1.2em"; // Change the fontSize.
}
</script>
<p id="myElem1" class="classExample">My First paragraph</p>
<p id="myElem2" class="classExample">My Second paragraph</p>
<form>
<fieldset>
<legend>Input Field</legend>
<label>Check Me : <input type="checkbox" name="TickMe" value="ticked" /></label>
<label>Check Me : <input type="checkbox" name="TickMe" value="ticked" /></label>
</fieldset>
</form>
<script>
document.querySelector('#myElem1').style.fontSize = "1.2em"; // Make the first paragraph 1.2em
document.querySelector('p').style.color = "#0D0"; // This will only affect the first paragraph
// You can also add event listeners...Again this will only affect the first checkbox.
document.querySelector('input[type=checkbox]').addEventListener('click', function(e){alert("You Checked Me");});
</script>
<p id="myElem1" class="classExample">My First paragraph</p>
<p id="myElem2" class="classExample">My Second paragraph</p>
<form>
<fieldset>
<legend>Input Field</legend>
<label>Check Me : <input type="checkbox" name="TickMe" value="ticked" /></label>
<label>Check Me : <input type="checkbox" name="TickMe" value="ticked" /></label>
</fieldset>
</form>
<script>
var classExample = document.querySelectorAll('.classExample'); // Get all the elements with class "classExample"
for(i=0; i<classExample.length; i++) {// Cycle through them
classExample[i].style.fontSize = "1.2em"; // Change the fontSize.
}
// Add an click listner to the element #myElem1 and #myElem2
var idExample = document.querySelectorAll('input[type=checkbox]');
for(i=0; i<idExample.length; i++) {// Cycle through them
idExample[i].addEventListener('click', function(e){alert("You Clicked me!");}); // Add the alert.
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment