Search code examples
javascriptparent-childgetelementbyidgetelementsbyclassnamejs-scrollintoview

Scroll into view by className to a paragraph that is a child of a child of an element - pure JS


I want to scroll to a specific paragraph that is a child of a child of an element

Below is a simplified version of my html.

I want to scroll to the paragraph with the className of ticketType. There are more paragraphs in my actual code so I want to target it by className.

There will be other paragraphs with this className that I don't want to scroll to, so I need to specifically target (and scroll to) the paragraph with className of ticketType within the element that has an id of ticket0.

{this.state.tickets.map((e, i) => {
return (

    <div className = "content createTicket" id={`ticket${i}`} >

    <form key={i}>
        <p className="warning ticketType">{this.state.tickets[i].errors.ticketType}</p>
        <div className="group">
            <input
                required
                type="text"
                value={this.state.tickets[i].ticketType}
                onChange={event => this.changeTicketDetails(event, 'ticketType', i)}
                placeholder="Ticket Name eg. General Admission"
            />     
        </div>
    </form>

    )

})}

This code is scrolling to the parent div:

document.getElementById(`ticket0`).scrollIntoView({behavior: "smooth"})

I am trying to get further options using:

document.getElementById(`ticket0`).children

but when I console.log this it isn't recognising the paragraph. I am getting:

HTMLCollection(2)
0: form
0: input

In CSS I could target it as #ticket0 < .ticketType

Is there something similar in Javascript


Solution

  • You get that console output because parentNode.children returns an HTMLCollection and not a single element.

    To achieve the desired behavior, you could try: document.querySelector('#ticket0 > .ticketType').scrollIntoView({behavior: "smooth"})

    or put another way: document.getElementById('ticket0').getElementsByClassName('ticketType')[0].scrollIntoView({behavior: "smooth"})

    or if you only care for the first child: document.getElementById('ticket0').firstElementChild.scrollIntoView({behavior: "smooth"})

    or if you care about the n-th child: document.getElementById('ticket0').children[n].scrollIntoView({behavior: "smooth"})