onlyforbopi
9/24/2018 - 6:27 AM

JS.DOM.AccessHtml.QuerySelector.Ex1

JS.DOM.AccessHtml.QuerySelector.Ex1

window.onload = init;

function init() {
  // we're sure that the DOM is ready
  // before querying it
  
  // add a shadow to all images
  // select all images
  var listImages = document.querySelectorAll("img");

  // change all their width to 100px
  listImages.forEach(function(img) {
    // img = current image
    img.style.boxShadow = "5px 5px 15px 5px grey";
    img.style.margin = "10px";
  });  
  
}

function addBorderToFirstImage() {
  // select the first image with id = img1
  var img1 = document.querySelector('#img1');

  // Add a red border, 3px wide
  img1.style.border = '3px solid red';  
}

function resizeAllImages() {
  // select all images
  var listImages = document.querySelectorAll("img");

  // change all their width to 100px
  listImages.forEach(function(img) {
    // img = current image
    img.width = 100;
  });
}

JS.DOM.AccessHtml.QuerySelector.Ex1

A Pen by Pan Doul on CodePen.

License.

<!DOCTYPE html>
<html lang="en">
<head>
  
<!--
///////////////////////////////////////////////
// ACCESS HTML ELEMENTS (SELECTOR API)

	// any css selector (id) can be passed as a parameter for these methods
	//
	// querySelector(selector) - will return the first element of the dom that matches
	//
	// querySelectorAll(selector) - returns a collectio nof HTML elements corresponding to all
	// elements matching the selector.
-->
  
  
  
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>querySelector and querySelector example 1</title>
</head>
<body>
  <button onclick="addBorderToFirstImage();">
    Add a border to the first image
  </button>
  <br>
  <button onclick="resizeAllImages();">
    Resize all images
  </button>
  <br>
  <p>Click one of the buttons above!</p>
<img src="https://mainline.i3s.unice.fr/mooc/Ntvj5rq.png" 
     id="img1"
     width=200 alt="image #1">
<img src="https://mainline.i3s.unice.fr/mooc/yiU59oi.gif" 
     width=200 alt="image #2">
<img src="https://mainline.i3s.unice.fr/mooc/6FstYbc.jpg" 
     width=200 alt="image #3">
<img src="https://mainline.i3s.unice.fr/mooc/L97CyS4.png" 
     width=200 alt="image #4">
</body>
</html>