JS: Add path to DOM element in string format returns a non-desired string as output

Viewed 172

In JavaScript, suppose I have a DOM element in a variable like this:

var first_part = document.querySelectorAll('.sizes.row > .selectric-wrapper > .selectric-items > .selectric-scroll > ul > li')

This returns an array with several list items.

Now I'd like to query somewhat deeper, but in my code, it depends which 'route' to take.

In some cases (name it 'scenario 1') I need this path:

document.querySelectorAll('.sizes.row > .selectric-wrapper > .selectric-items > .selectric-scroll > ul > li')[0].className

In other cases (name it 'scenario 2') I need this path:

document.querySelectorAll('.sizes.row > .selectric-wrapper > .selectric-items > .selectric-scroll > ul > li')[0].children[0].title

So what I tried was:

var second_part = ['[0].className','[0].children[0].title']

And then refer to for example scenario 1 like this:

var scenario_1 = first_part + second_part[0]

The result is this

"[object NodeList][0].className"

This is not what is required; I'd like to get the value of the className.

Does anyone know how to solve this?

2 Answers

Here is if the targeted element is one there is no need of calling querySelectorAll just use querySelector the following is an example

element = document.querySelector('.sizes.row > .selectric-wrapper > .selectric-items > .selectric-scroll > ul > li')
title = element.children[0].title
class_name = element.className

What is happening is here is because of how the javascript engine interprets the + sign between objects, what does it do in this case is simply calling toString method on the two objects and then concatenating the two strings together which is obviously not what you want.

You could do what you want like this in multiple different ways, one way is to save the selector string in a variable to make things shorter

const query = '.sizes.row > .selectric-wrapper > .selectric-items > .selectric-scroll > ul > li'
const scenario1 = document.querySelectorAll(query)[0].className
const scenario2 = document.querySelectorAll(query)[0].children[0].title
// dont forget to guard against null values

You could also nest query selector queries using the querySelector method it self. you could also take a look at lodash get method, which can do what you want

Related