html querySelector code example

Example 1: js select element by css selector

// First Element:
document.querySelector('.class')

// Multiple Elements:
document.querySelectorAll('.class')

Example 2: queryselector

var el = document.querySelector(".myclass");

Example 3: javascript queryselector

//Pretend there is a <p> with class "example"
const myParagraph = document.querySelector('.example');
//You can do many this with is
myParagraph.textContent = 'This is my new text';

Example 4: queryselector javascript

var element = document.querySelector("#myid .myclass p");

Example 5: js queryselector

const content = document.querySelector('.content');

const towns = ['Helsinki', 'Espoo', 'Vantaa'];

towns.forEach(city => {
    content.innerHTML += `<p>${city}</p>`;
});

Example 6: queryselector function in javascript

/*The querySelector() method returns the first element that matches a specified 
CSS selector(s) in the document. Note: The querySelector() method only returns 
the first element that matches the specified selectors. To return all the 
matches, use the querySelectorAll() method instead.*/

// for example 

//for class
document.querySelector(".ClassName")

// for id 
document.querySelector("#ID")

// etc.

Tags:

Html Example