js get element code example

Example 1: get element in js

//<div id="demo-id"></div>
var elem1 = document.getElementById("demo-id");
//<div class="demo-class"></div>
var elem2 = document.getElementsByClassName("demo-class");
//<div name="demo-name"></div>
var elem3 = document.getElementsByName("demo-name");
//<p>Some text</p>
var elem4 = document.getElementsByTagName("p");

//<div id="demo-id"></div>
var elem1 = document.querySelector("#demo-id");
//<div class="demo-class"></div>
var elem2 = document.querySelectorAll(".demo-class");
//<div name="demo-name"></div>
var elem3 = document.querySelectorAll('[name="demo-name"]');
//<p>Some text</p>
var elem4 = document.querySelectorAll("p");

Example 2: how to get element of an array in javascript

var value = [a,b,c,d];

var value_b = value[1];

Example 3: get element by id in javascript

document.getElementById("YourElementId");

Example 4: get id of element javascript

var element = document.getElementsByTagName("div")[0];
var id = element.id;

Example 5: get element in javascript

// Selecting an Element by id:
document.getElementById("elem-id");
// Selecting  Elements by class:
document.getElementsByClassName("elem-class");
// Selecting Elements by tag name: 
document.getElementsByTagName("div");
//  Selecting Elements by name:
document.getElementsByName("elem-name");
/* This method is like a jQuery selector 
( #elemId -> id, .elemClass -> class, h1 -> tag name) */
document.querySelector("h1");

Tags:

Java Example