1

Give me some tips please, I have an object with data - I get it with parentNode. Here is my data in the object:

data in the object

I need to get data of element ul.district-areas. I can do this by its key - 2, but I would like to explicitly indicate that I need an element with a specific class. Is it possible to do this, and if so, how?

Thanks

6 Answers 6

1

You should convert the Dom List to an array and then find the className as per your Match.

  1. Approach for finding only direct child
     Array.from(parentNode).filter((dom) => dom.className.contains("district-areas"))

if You like to find the DOM specifically (ie. ul.district-areas) then add tagName as well

    Array.from(parentNode).filter((dom) => dom.tagName === "UL" && dom.className.contains("district-areas"))

  1. Approach for finding a Dom which is a Nested-child. From parentNode(parent Dom element) finds the child element which is in any level.
parentNode.querySelector('ul.district-areas')

I hope this helps you.

Sign up to request clarification or add additional context in comments.

Comments

1

You can do check if an element has a class via the classList property:

myElement.classList.contains("this-class")

In you case, I would filter the array and return only those elements that match the specified classes

var filteredArray = myArray.filter(function(element){ return element.classList.contains("this-class"); });

If your "array" is not actually an array and is actually a HTMLCollection, then you would need to convert it to an array first:

myArray = Array.from(myArray)

Comments

1

you could do the following:

Array.from(parentNode).filter(it => it.localName == "ul" && it.className == "district-areas")

Comments

1

You can use Javascript Array.From() to filter out your exact matching see the below screen shots for example

Find/Filter Control From Array

Comments

0

Just use the function querySelector('.district-areas'). Prefixing the name with a dot indicate it's a class.

Comments

0

if you want to convert object to array You can use Object.values()

Input : var object = { 0: '23', 1: 'geeksforgeeks', 2: 'true' };
        console.log(Object.values(object));
Output : Array ["23", "geeksforgeeks", "true"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.