简体   繁体   中英

How to traverse dom dot notation with a div element with an id

I would like to traverse the dom with just dot notation

eg document.body

Under body I have a div with id mydiv . I know about querySelector() or getElementById() but that's not my question. I simply want to open the JS console and using dot notation drill down into elements using dot notation.

document.body.#mydiv # doesnt work

Would like the console to return #mydiv with the ability to expand and look at it in Chrome

You will need to use firstElementChild , lastElementChild or children to get to the next child. .children will give you an array of all the children of a node. You can loop through it and find the div with specific id. Here is an example

document.querySelector('body').children[2].firstElementChild.children[0]

This is get the 2nd child of the body's first child's first child.

getElementById is more easier and cleaner in your case.

To traverse tree using dot notation you need to use children nodes

 console.log( myDiv.children[0].innerText ); 
 <div id="myDiv"> <div>Hello</div> </div> 

For an element with id you can always use below in console

$('#myDiv');

or

$$('#myDiv')

This will show that element in console, from there you can see all details of that element.

This should also work with any selector

eg: Try below in this page

$$('.user-details')

You will see something like this

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM