Home > Software design >  Javascript - find an element
Javascript - find an element

Time:11-10

I'm making an extension and trying to access the element and print it out to the console.log()

<li id="ember7026" class="ember-view c-tab__list__item publicConversation" data-test-id="public-conversation" data-count="1" aria-expanded="false" aria-selected="false"><span class="is_new_flag">NEW</span>Public
</li>

At this point I'm trying to access data-count, however didn't manage to find a way.

I have accessed the whole list by:

var x = document.querySelector("#ember7026")

CodePudding user response:

B"H

Original question: "Javascript - find an element"

So it seems like you have already found the element and have a reference to it, and now what you're looking to do is to get a certain attribute from the element reference that you have

To do so simply use the getAttribute function, like

myReferenceToHTMLNode.getAttribute("data-count")

Although I may have misunderstood the question, it's also possible that you're trying to find all elements with a certain attribute (in this case, data attribute) value instead of relying on the individual id.

In that case you can simply do something like

document.querySelector('li[data-count="1"]')

To print a JavaScript value to console, simply call console.log on the Javascript value you want to print, so for example

console.log(ember7026.getAttribute("data-count"))

CodePudding user response:

You can usedataset API to get the test-id.

HTMLElement.dataset

const element =  document.getElementById("ember7026");
const data = element.dataset;

console.log("The ID:", data.testId);
console.log("Count:", data.count);
<li id="ember7026" class="ember-view c-tab__list__item publicConversation" data-test-id="public-conversation" data-count="1" aria-expanded="false" aria-selected="false"><span class="is_new_flag">NEW</span>Public
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related