javascript get element by attribute name code example

Example 1: javascript get element by class

var elementsArray = document.getElementsByClassName("someclassname");

Example 2: check the doc name in javascript

var path = window.location.pathname;
var page = path.split("/").pop();
console.log( page );

Example 3: javascript get attribute

//HTML
//<div id="elem" data-id="4hJ3s"></div>

var elem = document.getElementById("elem");
elem.getAttribute("data-id"); // "4hJ3s"

Example 4: javascript element read attribute

document.getElementById('id1').getAttribute('attribute');

Example 5: how to get element by attribute value in javascript

document.querySelectorAll('[data-foo="value"]');

Example 6: js get element by attribute

//find first element with "someAttr" attribute
document.querySelector('[someAttr]')

Tags:

Html Example