Choose a node in Javascript that contains a particular attribute value

In the provided XML data:

<elements>
        <product id="1">
                <brand>xxxxxxx</brand>
                <dci>xxxxx</dci>
                <therapeutic_area>xxxxxx</therapeutic_area>
        </product>
        <product id="2">
                <brand>xxxxxx</brand>
                <dci>xxxx</dci>
                <therapeutic_area>xxxx</therapeutic_area>
        </product>
        <product id="3">
                <brand>xxx</brand>
                <dci>xxxx</dci>
                <therapeutic_area>xxxxx</therapeutic_area>
        </product>

I am looking to select a node with a specific attribute value, such as 2.

I attempted the following code without success:

alert(xmlDoc.getElementsByTagName("product")[0].getAttributeNode("2"));

Any help or guidance on this matter would be greatly appreciated. Thank you.

Answer №1

Here is a better way to approach it:

var items=xmlDoc.getElementsByTagName("product");
for (x=0;x<items.length;x++)
{
     if(items[x].getAttribute("id")==2){
        // Node identified successfully
     }
} 

Answer №2

var xmlfile = "<elements><product id=\"1\"><brand>xxxxxxx</brand><dci>xxxxx</dci><therapeutic_area>xxxxxx</therapeutic_area></product><product id=\"2\"><brand>xxxxxx</brand><dci>xxxx</dci><therapeutic_area>xxxx</therapeutic_area></product><product id=\"3\"><brand>xxx</brand><dci>xxxx</dci><therapeutic_area>xxxxx</therapeutic_area></product></elements>";

var parser = new DOMParser();

xmlDocument = parser.parseFromString(xmlfile,"text/xml");

var products = xmlDocument.getElementsByTagName("product");

for (var i = 0; i < products.length; ++i) {
    if (products[i].getAttribute("id") == 2) {
       // product id is 2.   
    }
}

http://jsfiddle.net/dvgLhw66/ <-- this fiddle works correctly.

You've mistakenly used getAttributeNode instead of getAttribute, make sure to use the correct prototype for your code.

Answer №3

let targetNode = xmlDoc.getElementsByTagName("product");
for (let i of targetNode) {
    if (i.getAttribute("id") == "2") {
        console.log("Match found!");
    }
}

Answer №4

I'm not quite sure what you're attempting to accomplish here, but you might want to consider using a code snippet similar to this.

alert(document.querySelector("[id='2']").querySelector('brand'));

For more information, check out the MDN Web Docs on querySelector.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using PHP to interact with Xbox API

Recently, I have been utilizing xapi.us to fetch my XBL clips through their API. By using the code snippet below, I was able to display the result on my webpage... <?php $uxid = rawurlencode("PROFILE ID"); $ch = curl_init(); curl_setopt($ch, CURLOPT_U ...

Show a malfunction with the `show_message` function

How can I show the die() message in if($allowed) in the same location as the move_uploaded_file result? <?php $destination_path = $_SERVER['DOCUMENT_ROOT'].'/uploads/'; $allowed[] = 'image/gif'; $allowed[] = ' ...

Is it better to set the language of Puppeteer's Chromium browser or utilize Apify proxy?

Looking to scrape a website for French results, but the site supports multiple languages. How can I achieve this? Is it best to configure Puppeteer Crawler launch options using args, like so: const pptr = require("puppeteer"); (async () => { const b ...

retrieve the client's time zone based on browser information

Is there a foolproof method for obtaining the timezone of a client's browser? I have come across some resources, but I am looking for a more reliable solution. Automatically detect time zone using JavaScript JavaScript-based timezone detection ...

What is the best way to utilize jQuery.post in order to push JSON data to a php script?

I have a JSON object in my JavaScript code stored in the variable dataStore. I've confirmed that JSON.stringify is working correctly by testing it with console.log(). However, as someone new to jQuery and CGI applications, I may be missing something. ...

How come the 'color' property in the material-ui TextField functions properly, while the 'borderColor' property does not work as expected?

I am trying to show a TextField in orange color: <TextField id={field_meta.name} label={field_meta.title} defaultValue={field_meta.value? field_meta.value: ""} onChange={this.handleChange} margin="normal" inputProps={{style: {bo ...

Interactive menu dropdown failing to function properly

I am working on dynamically creating a dropdown javascript menu using javascript. After fetching menu items from a MySQL database in PHP and storing them in a JavaScript array, I aim to generate the menu dynamically through a JavaScript function. This way ...

Can we improve the coding of this as it seems inefficient and uses up too much room?

Do you think there is a more efficient way to write this code? It seems quite impractical and takes up a lot of space. Essentially, it's about the random chance of obtaining a rarity, like acquiring an Uncommon sword. if (Math.random() * 100 < 100 ...

ng-repeat did not properly listen for changes in the radio box selection

Feeling a bit confused here. I'm trying to call a function on change and pass the obj to it. From what I understand, since it's bound to the selected obj, I should be able to just use ng-model. However, in this situation, nothing happens when I s ...

Using a loop to pass a template to a function and create a dynamic component

I am currently attempting to dynamically generate a component while looping through a list. However, I have encountered an issue where the template cannot be passed to the function for creating the component. The error message indicates that the viewCont ...

How can I pass an array object from an HTML form that adheres to a Mongoose schema

I have this HTML form that I'm using to create a new document in my mongo database. The document represents notes given to a teacher based on various criteria. I am storing the notes in an array within the note property, each object containing the aut ...

Are there any tools available that can convert ThreeJS code into WebGL?

Are there any existing tools that can convert ThreeJS to WebGL? Or, could you provide guidance on creating a converter for ThreeJS to WebGL? ...

Access the content of each cell in a table using JavaScript

I need help with a scenario involving a table that has 4 rows, where the 4th row contains a textbox. When the "onchange" event of the textbox is activated, I want to retrieve the data from the cells in that specific row and transfer it to another table. It ...

The NextJS homepage and API endpoint are combined on a single page

In my Next.js application, I have multiple pages and I want the component loaded at http://localhost:3000/someEndpoint to be exactly the same as the one loaded at http://localhost:3000/ I have already created an index.js file, but I am unsure how to creat ...

I'm attempting to retrieve information from my vuex store, however, encountering an error in the process

I've encountered an issue with vuex getters while working on my project. I have a route that showcases all users, and upon visiting this route, the AllUsers.vue component is displayed. Within this component, I'm utilizing the UsersList.vue compo ...

retrieve the information from a specific field within the store and store it in an array

Perhaps this is a question that pertains to using pure JavaScript, but for some reason I can't seem to figure it out. I am currently working on extjs4.2 using Sencha Architect and have received a JSON response from the server in the following format: ...

Having trouble saving user input from a form to a database using axios, mongodb, and vue?

I am a beginner in working with Vue and I'm currently facing an issue while trying to submit user input data to my MongoDB using axios. Although the data from the database is displayed on the page, I can't seem to get the form input data to succe ...

What steps do I need to take to set up an SSH CLI Endpoint on my NodeJS Server?

Recently, I came across a library called ssh2 which is designed to handle connections to SSH Servers and also host SSH Servers. However, when attempting to use the code provided on their NPM page, I encountered a persistent issue where the shell would clos ...

In Angular, what is the best way to update the quantity of an item in a Firestore database?

Whenever I attempt to modify the quantity of an item in the cart, the quantity does not update in the firestore database. Instead, the console shows an error message: TypeError: Cannot read properties of undefined (reading 'indexOf'). It seems li ...

Check the document's location if the page contains a class with a specific value

I am encountering an issue while using PHPMailer. I am trying to redirect the page after submitting a form and display a success popup window. After successfully submitting the form, a message is displayed in a popup window (JavaScript adds a class ' ...