Selectors

All about Selectors in JavaScript


Select an Element ☝

  • document: the DOM or tree representation of the HTML
  • querySelector - selects, like in CSS, the first element instance
document.getElementByClassName("elementClass")  // returns array of nodes
document.getElementById("elementId")    // returns a single element
document.getElementsByTagName('div')    // returns an array of all <div> elements
document.getElementsByName('interests') // returns an aarray of all elements that matches -> <input name="interests">
 
document.querySelector("#elementId")    // returns the first element that matches the selector
document.querySelector('.elementClass') // returns the first element 

Retrieve Text from Element ↩

Retrieve the text of an HTML element using .value

let login = document.getElementId("loginId").value;
// => "Sign In"

Modify Attribute ⬆️

getAttribute() - setAttribute()

We can get any attribute of any HTML element: src, class, id, href, data-*, etc.

document.querySelector("#theImage").getAttribute("src")
// => images/Testudo01.jpg
 
document.querySelector("#theImage").setAttribute("src", "images/Testudo02.jpg")

Access/Modify the attribute directly

document.querySelector("#myImage").src = "testudo1.jpg"

getAttribute vs querySelector().src

imageElement.getAttribute("src"); // value of src
// images/Testudo1.jpg
 
document.querySelector("#myImage").src // full path
// http://url/to/path/Testudo1.jpg

Modify Class Attribute ⬆️

Suppose we have the following HTML element:

<p id="my-paragraph" class="red">Hello, world!</p>

replace()

element.classList.replace("red", "blue");

remove() and add()

element.classList.remove("red"); 
element.classList.add("blue");

toggle()

  • If the element has the "blue" class, then removes it (returns false)
  • if it doesn't have it, then adds it (returns true)
element.classList.toggle("blue");

Modify Page with innerHTML ⬆️

  • document.querySelector().innerHTML - add/replace HTML code inside an element by ID (e.g div)
document.querySelector("#mydiv").innerHTML = table // replace a new content to the element
 
document.querySelector("#mydiv").innerHTML += table // add new content to the element

document.writeln()

  • Write a string of text or HTML code to the document, followed by a line break.
  • It is typically used to add new content to the end of a document or a specific element
// Write a string to the end of document
document.writeln("Hello, world!");
 
// Write HTML code at the end to a specific element
document.getElementById("myElement").writeln("<p>Hello, world!</p>");