简体   繁体   中英

How to target second child element of a div using JAVASCRIPT

I'm not sure if this is possible, I rarely do when I ask questions on this site, but everyone keeps telling me to use jQuery to do so. I make websites, but I am VERY novice at all of this and would prefer to get solid grip on Javascript before moving forward.

Anyways, my question is "Is it possible to target a second child (ie

<div>
   <div></div>
   <div></div> <!--This one-->
</div>

using JAVASCRIPT in order to manipulate it? If so, how?"

My previous attempt didn't work, I had a strong feeling it wouldn't but, all the same.

function activateEvent(obj) {
    obj.secondChild.style.display="block";};
obj.firstElementChild.nextElementSibling

( doesn't work in IE8 )

Or

obj.children[1]

you can use Jquery API also:-

:nth-child() Selector

:eq() Selector

You really should try to learn jQuery because it will make things a lot easier for you. Get the basics from plain Javascript and then learn a library like jQuery. you just need to load it into your website, then you can target the element in your exemple using: $('.parent div:nth-child(2)') It's that easy.

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