St3ph3n92
St3ph3n92

Reputation: 356

Select an object property within an attribute of the DOM

I looked at this thread but it didn't help: Find an element in DOM based on an attribute value

I need a Vanilla JS solution to select a username that is in a custom attribute of an <a> tag in the DOM. I used const users = document.querySelectorAll('a[metadata]') which returns a NodeList of all the <a> tags with all their attributes. If I type console.log(users[0]), I get:

<a href="#" class="btn-normal" metadata="
{
'username':'johnny134',
'category':'shoes',
'summary':'Just a guy called Johnny',
'userId':1223432432
}"
</a>

To access the username, I have tried const usernames = document.querySelectorAll('a[metadata="username"]'); but just get back undefined. I think my issue is that username is in an object and I can't figure out how to select it.

Thanks in advance

Upvotes: 0

Views: 729

Answers (1)

Mubaraq Wahab
Mubaraq Wahab

Reputation: 302

First, note that document.querySelectorAll returns a list of elements that match the given query, not a list of the values of attributes of those elements that you specify in the query.

From const users = document.querySelectorAll('a[metadata]'), you can get the metadata attribute of, say, the first element, like so:

const metadata0 = users[0].getAttribute("metadata");

And then, since it's a JSON string, you parse it:

const user0 = JSON.parse(metadata0);

Now you can use user0 like a regular JavaScript object:

user0.username
// johnny134

P.S. The JSON in the metadata attribute is not valid, and you may get an error when you try to parse it. Use double quotes in JSON, not single quotes.

Upvotes: 1

Related Questions