1

here is my code,

var selectedLabel = $(".alllabel li.active").attr("id");

I tried

    var selectedLabel = parent.document.getElementsByClassName(".alllabel li.active")
                       .getAttribute("id");

But undefined value gets. pls, help me out of here ..!

1
  • It's not clear what you're asking. Are you asking how to do the equivalent operation to the jQuery code you showed using the DOM directly? If so, this question is relevant. Commented Oct 9, 2020 at 10:11

2 Answers 2

1

If your question is how to do the same thing as the jQuery code you showed using the DOM directly, the simplest way is:

var selectedLabel = document.querySelector(".alllabel li.active").id;

querySelector finds the first element in the DOM that matches a given CSS selector, and the id attribute has a reflected property called id.

Live Example:

var selectedLabel = document.querySelector(".alllabel li.active").id;
console.log(selectedLabel);
<ul class="alllabel">
    <li id="not-active">not-active</li>
    <li class="active" id="the-active-one">the active one</li>
</ul>

However, unlike the code using jQuery, that will throw an error if the element isn't found at all. If you want to get undefined (which is what jQuery would give you in that case), you'd do this:

var element = document.querySelector(".alllabel li.active");
var selectedLabel = element ? element.id : undefined;

Or with ES2021's optional chaining operator:

const selectedLabel = document.querySelector(".alllabel li.active")?.id;

That would give you null rather than undefined if not found, but...close enough. If you really, really wanted undefined, you could also use ES2021's nullish coalescing operator:

const selectedLabel = document.querySelector(".alllabel li.active")?.id ?? undefined;

If you wanted to get the value of an attribute that didn't have a reflected property, you'd use getAttribute as in your question. For instance, here's the first code block in this answer using getAttribute instead:

var selectedLabel = document.querySelector(".alllabel li.active").getAttribute("id");

But again, you don't need to do that with id.

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

Comments

0

getElementsByClassName will return an array, while the getAttribute method should be executed on a single node. In your case, you can try:

parent.document.getElementsByClassName(".alllabel li.active")[0].getAttribute("id");

4 Comments

error like ...uncaught TypeError: Cannot read property 'getAttribute' of undefined
please use attr instead of getAttribute.
@WaqarAkram - Why? the OP seems to want to replace their jQuery code with DOM code.

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.