0

Trying to get the value of a specific tag in HTML, but I can't find a proper way to do it.

Let's say I have the following HTML code:

<body id="en" class="that-great-class " number_id="1534" support="clp" source="desktop">

How can I get the value from number_id, support and source ? Already tried this but doesn't work.

document.getElementsByTagName("number_id");

Thanks.

4 Answers 4

1

So your js is only slightly off, you are using getElementsByTagName which will get HTML elements by their tag e.g. body tag, header tag, div tag and so on.

You are wanting to get the attribute of the body tag so you first would need to get the body tag.

const bodyTag = document.getElementsByTagName("body")[0];

This gets all elements with the tag name of body and puts them in the array, but there should only be 1 body tag so you get the first.

You then want to get the attribute of 'number_id', to do this, you would do

const numberId = bodyTag.getAttribute("number_id");
Sign up to request clarification or add additional context in comments.

Comments

1
document.querySelectorAll('[number_id="1534"]')

The related docs are Attribute_selectors and querySelectorAll

Comments

1

Your method name is incorrect it should be plural if you use tagName getElementsByTagName

But didn't actually correct with what you are trying to use

Getting element by tag means like HTML tags Ex - li, h1 body not their attributes

Use querySelector instead.

const el = document.querySelector("[number_id='1534']")
console.log(el)
<body id="en" class="that-great-class " number_id="1534" support="clp" source="desktop">

Comments

0

Have you tried this?

var id = document.getElementById("en").getAttribute("number_id");

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.