Home > Net >  Get inner HTML to id and tag
Get inner HTML to id and tag

Time:01-24

With the following TypeScript code

let inventory: HTMLElement = document.querySelector("dialog[type=inventory]");

I get the following HTML element

<dialog type="inventory">
   <button type="button">Exit</button>
   <ul>
      <li id="Blue">
         <name>Blue item</name>
         <amount>2</amount>
      </li>
      <li id="Red">
         <name>Red item</name>
         <amount>1</amount>
      </li>
   </ul>
</dialog>

I am trying to get the inner HTML value for amount and a specific id. For example, id="Red" and its <amount> value.

How can this be done with JavaScript?

I tried as follows, but then I cannot select the id for which I want the amount

inventory: HTMLElement = document.querySelector("dialog[type=inventory] > ul > li > amount");
console.log(inventory.innerHTML); // Prints amount 2

I could imagine using querySelectorAll() and looping over the values, but there should be a better solution.

CodePudding user response:

You can add the ID to your selector:

"dialog[type=inventory] > ul > li#Red > amount"

You could also simplify as you don't need all elements in the tree, just the ones that allow for selection.

"dialog[type=inventory] #Red amount"

CodePudding user response:

By utilizing the querySelector method, you can target a specific li element with a specific id, and subsequently access the text within the amount element by using the textContent property.

example :

let inventory = document.querySelector("dialog[type=inventory]");
let element= inventory.querySelector("li#Red");
let amount = element.querySelector("amount").textContent;

CodePudding user response:

As another answerer states, you can add the ID as a requirement when selecting the li element:

dialog[type=inventory] > ul > li#Red > amount

However, since you can only have one element with the same ID on the page at the same time, you can actually simplify this to just

li#Red > amount

This really feels like an XY problem though, where you're asking to do one thing, but really you only need to do this because of some greater overarching problem. Ideally you shouldn't be looking up the contents of your HTML tree to find values like this, because it's super fragile and unreliable (e.g. if you need to change the structure for styling reasons, etc, you now break all of this logic, and TypeScript won't be able to save / warn you about it at all).

A better approach would be to keep a copy of your data model in JavaScript, and then use that to generate the HTML.


It's also worth noting that neither <name> nor <amount> are valid tags in HTML5. You are allowed to create custom tags, but they must contain at least one - character in their names, e.g. <inventory-name> rather than <name>.

CodePudding user response:

const amount = document.querySelector("dialog[type='inventory'] ul #Red amount").innerHTML;
console.log(amount); // Prints "1"
  • Related