I'm trying to access the specific child by class name but it's not working it gives me all inner html used in ul?
var element = document.getElementsByClassName("inner")[0].innerHTML;
console.log(element);
<ul id="list" class="inner">
<p>paragraph</p>
<li><a href="" class="hom" id="hoo">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Classes</a></li>
<li><a href="">Services</a></li>
<li><a href="">Gallery</a></li>
<li><a href="">Teachers</a></li>
<button ><a href="" id="btn-1" >Join class</a></button>
</ul>
</nav>
document.getElementsByClassName
returns an array with all the elements
that have said class. document.getElementsByClassName('inner')[0]
would just be selecting the first and only element with such class (Your ul
).
If you need to access a specific child of that element, you would need to use the children
property and then you can use any index that matches an existing child.
var element=document.getElementsByClassName("inner")[0].children[0].innerHTML; console.log(element);
<ul id="list" class="inner"> <p>paragraph</p> <li><a href="" class="hom" id="hoo">Home</a></li> <li><a href="">About</a></li> <li><a href="">Classes</a></li> <li><a href="">Services</a></li> <li><a href="">Gallery</a></li> <li><a href="">Teachers</a></li> <button ><a href="" id="btn-1" >Join class</a></button> </ul> </nav>
I would advise against document.getElementsByClassName
and just use document.querySelector('.inner')
instead to select the element.
Instead of using getElementsByClassName
you can use querySelector to easily target the paragraphs innerHTML.
See example below:
var element = document.querySelector(".inner p").innerHTML; console.log(element);
<ul id="list" class="inner"> <p>paragraph</p> <li><a href="" class="hom" id="hoo">Home</a></li> <li><a href="">About</a></li> <li><a href="">Classes</a></li> <li><a href="">Services</a></li> <li><a href="">Gallery</a></li> <li><a href="">Teachers</a></li> <button><a href="" id="btn-1" >Join class</a></button> </ul> </nav>
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.