0

I have an array and this code:

console.log(trips_array[0].outerHTML)

prints out this:

<trip origin="SFIA" destination="FRMT" fare="11.65" origTimeMin="7:47 AM" origTimeDate="07/23/2016 "
    destTimeMin="9:18 AM" destTimeDate="07/23/2016" clipper="4.35" tripTime="">
  <leg order="1" transfercode="N" origin="SFIA" destination="BALB" origTimeMin="7:47 AM" origTimeDate="07/23/2016" 
    destTimeMin="8:06 AM" destTimeDate="07/23/2016" line="ROUTE 2" trainHeadStation="PITT" trainIdx="8"/>
  <leg order="2" transfercode="N" origin="BALB" destination="BAYF" origTimeMin="8:13 AM" origTimeDate="07/23/2016"
    destTimeMin="8:54 AM" destTimeDate="07/23/2016" line="ROUTE 12" trainHeadStation="DUBL" trainIdx="8"/>
</trip>

How can I get the value of the attributes? For instance the trip origin and the leg origin?

3 Answers 3

1

Use something like the following to get the value of the "origin"-attribute of "trip".

trips_array[0].getAttribute("origin");

You can get the "origin"-value for the first leg-element like that:

trips_array[0].children[0].getAttribute("origin")
Sign up to request clarification or add additional context in comments.

2 Comments

Could you also tell me how I could get all the leg attributes? So basically what is the best way to iterate thru the legs to get the attrs.
@SzilardMagyar something like for (var i = 0;i<trips_array[0].children.length;i++) { trips_array[0].children[i].getAttribute("origin"); //Your value }
1

Use getElementsByTagName and getAttribute like below.

//  That returns an array
var trips = document.getElementsByTagName('trip');

trips[0].getAttribute("origin");

Comments

1

The easiest way to get the values of the attributes would involve using jQuery. Thus, you have two options:

  1. Get all the origins, irrespective of whether they belong to trip elements or to leg elements. In that case, the solution is:

    console.log($("trip, trip leg").attr("origin"));

  2. Get the origins of the trip and leg elements separately. In that case, the solution is:

    console.log($("trip").attr("origin"));

    console.log($("trip leg").attr("origin"));

The latter solution is more verbose, but it is more helpful if, instead of logging the attributes to the console, you want to save them in variables.

Comments

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.