5

I want to get the element using javascript without using its ID( html id="somethin" ) or a class.

Something like.....

var whatIWantedToSelect = document.html;

OR Something like.....

var whatIWantedToSelect = document.getElementsByTagName('html')[0];

Please, see the below picture to see the exact DOM element that I want to access via javascript.

The DOM element that I want to select

asked Jun 14, 2020 at 17:18

3 Answers 3

15

var whatIWantedToSelect = document.html;

The HTML element is the document.documentElement.

var whatIWantedToSelect = document.getElementsByName('html')[0];

getElementsByName matches elements by their name attribute. You are looking for getElementsByTagName.

answered Jun 14, 2020 at 17:19
Sign up to request clarification or add additional context in comments.

Comments

6

The root <html> element is available as document.documentElement. So there is no need to select it by tag name (which would have worked too, but you had getElementsByName instead of getElementsByTagName).

Docs: https://developer.mozilla.org/en-US/docs/Web/API/Document/documentElement

var whatIWantedToSelect = document.documentElement
answered Jun 14, 2020 at 17:20

Comments

3

You can use getElementsByTagName function as follows:

let html = document.getElementsByTagName('html')[0];
console.log(html);
html.addEventListener("click",function(){
 console.log("clicked")
})
html.click();
<html></html>

answered Jun 14, 2020 at 17:19

1 Comment

but my event listener is not working when document.getElementsByTagName('html')[0].click(); called. But if I clicked somewhere b mouse it works, Why?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.