Search code examples
javascripthtmljqueryxmlfind

Jquery XML find where attribute equals a specific value?


I have a Jquery website that pulls and displays a specific value from an XML source that is structured like so

<alerts>
<alert type="FIRE" status="CLEAR" id="xxxxxx" client_id="xxxxxx" grouping="xxxxxx">
    <alert_location name="xxxxxx"/>
    <template name="FIRE_CLEAR"/>
</alert>
    <alert type="LIGHTNING" status="CLEAR" id="xxxxxx" client_id="xxxxxx" grouping="xxxxxx">
    <alert_location name="xxxxxx"/>
    <template name="LIGHTNING_CLEAR"/>
</alert>

it collects the Lightning template name value being "LIGHTNING_CLEAR" in jquery by using:

var lightXML = $(xml).find('template').eq(1).attr("name");

This works fine until the xml provider removes the fire alerts for winter and then i have to edit the code every 6 months to use

var lightXML = $(xml).find('template').eq(0).attr("name");

I have searched for some answers without luck but is it possible to use find to ensure it always pulls the attribute value from the alert where type="LIGHTNING"?


Solution

  • You can use an attribute selector to find the template by the name attribute:

    var lightXML = $(xml).find('template[name="LIGHTNING_CLEAR"]').attr("name");
    

    The same using an interpolated variable:

    var templateName = 'FIRE_CLEAR'; // or 'LIGHTNING_CLEAR'
    var lightXML = $(xml).find(`template[name="${templateName}"]`).attr("name");