Tommy Riley
Tommy Riley

Reputation: 57

Get element from object (array) by its class

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

Upvotes: 1

Views: 2583

Answers (6)

Ravi Makwana
Ravi Makwana

Reputation: 2916

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"]

Upvotes: 0

Karan Ekkawala
Karan Ekkawala

Reputation: 327

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

Find/Filter Control From Array

Upvotes: 1

pero_hero
pero_hero

Reputation: 3194

you could do the following:

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

Upvotes: 1

prasana kannan
prasana kannan

Reputation: 676

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.

Upvotes: 1

Rylee
Rylee

Reputation: 1656

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)

Upvotes: 1

ariel
ariel

Reputation: 16140

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

Upvotes: 0

Related Questions