How to get attribute of child anchor with HtmlAgilityPack?




I am learning `HtmlAgilitiPack` and I want ask you, how to get value(**I want get this value**):


From HTML page:



```
<div id="js_citySelectContainer" class="select_container city_select shorten_text replaced"> 
<span class="dropDownButton ownCity coords">
<a>i want get this value</a>
</span>
</div>

```

C# code:



```
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html);
Console.writeln(echo i want get this value);

```

I tried: 



```
doc.DocumentNode.Descendants("span").Where(s => s.GetAttributeValue("class", "") == "dropDownButton ownCity coords").First().InnerText;

```

But it doesnt work, can you help me? Thank you.
You can use the XPATH syntax:



```
var span = doc.DocumentNode.SelectSingleNode("//span[@class='dropDownButton ownCity coords']");
var anchorText = span.ChildNodes["a"].InnerText;

```

You can also use LINQ:



```
var anchorTexts = 
    from span in doc.DocumentNode.Descendants("span")
    where span.GetAttributeValue("class", "") == "dropDownButton ownCity coords" 
    from anchor in span.Descendants("a") 
    select anchor.InnerText;
string anchorText = anchorTexts.FirstOrDefault();

```
You could achieve this with a simple `for` loop:



```
var min = 12,
    max = 100,
    select = document.getElementById('selectElementId');

for (var i = min; i<=max; i++){
    var opt = document.createElement('option');
    opt.value = i;
    opt.innerHTML = i;
    select.appendChild(opt);
}

```

[JS Fiddle demo](https://jsfiddle.net/davidThomas/NX3ac/).


[JS Perf](https://jsperf.com/) comparison of both mine and [Sime Vidas' answer](https://jsperf.com/comparison-of-loops), run because I thought his looked a little more understandable/intuitive than mine and I wondered how that would translate into implementation. According to Chromium 14/Ubuntu 11.04 mine is somewhat faster, other browsers/platforms are likely to have differing results though.







**Edited** in response to comment from OP:



> 
> [How] do [I] apply this to more than one element?
> 
> 
> 



```
function populateSelect(target, min, max){
    if (!target){
        return false;
    }
    else {
        var min = min || 0,
            max = max || min + 100;

        select = document.getElementById(target);

        for (var i = min; i<=max; i++){
            var opt = document.createElement('option');
            opt.value = i;
            opt.innerHTML = i;
            select.appendChild(opt);
        }
    }
}
// calling the function with all three values:
populateSelect('selectElementId',12,100);

// calling the function with only the 'id' ('min' and 'max' are set to defaults):
populateSelect('anotherSelect');

// calling the function with the 'id' and the 'min' (the 'max' is set to default):
populateSelect('moreSelects', 50);

```

[JS Fiddle demo](https://jsfiddle.net/davidThomas/NX3ac/1/).


And, finally (after quite a delay...), an approach extending the prototype of the `HTMLSelectElement` in order to chain the `populate()` function, as a method, to the DOM node:



```
HTMLSelectElement.prototype.populate = function (opts) {
    var settings = {};

    settings.min = 0;
    settings.max = settings.min + 100;

    for (var userOpt in opts) {
        if (opts.hasOwnProperty(userOpt)) {
            settings[userOpt] = opts[userOpt];
        }
    }

    for (var i = settings.min; i <= settings.max; i++) {
        this.appendChild(new Option(i, i));
    }
};

document.getElementById('selectElementId').populate({
    'min': 12,
    'max': 40
});

```

[JS Fiddle demo](https://jsfiddle.net/davidThomas/NX3ac/148/).


References:


* [`node.appendChild()`](https://developer.mozilla.org/en/DOM/node.appendChild).
* [`document.getElementById()`](https://developer.mozilla.org/en/DOM/document.getElementById).
* [`element.innerHTML`](https://developer.mozilla.org/en/DOM/element.innerHTML). As I mentioned, the sample code will be updated soon. Here's the info I received:

·         To set the “Fit one full page to screen” option

o    This is done on the article metadata, the field is fitToScreen

{

                “entityName”: “helloworld”,

                “entityTitle”: “Hello World”,

                “entityType”: “article”,

                “fitToScreen”: true,

                …

}

·         To set the “Enable horizontal swiping within PDF”

o    This is done when uploading PDF to the ingestion service, set the URL parameter hoirzontalSwipe

[https://ings.publish.adobe.io/publication/{{publication-id}}/article/{{entityName}};version={{versio...](https://ings.publish.adobe.io/publication/{{publication-id}}/article/{{entityName}};version={{version}}/contents/folio?horizontalSwipe=true)

o    By default, the horitzontalSwipe is set to false (i.e. if the URL parameter is not set)

o    If the horitzontalSwipe is set to true but fitToScreen is set to false, then the ingestion service will throw an error




[View solution in original post](/t5/adobe-experience-manager-mobile/upload-pdf-files-to-aemm-with-options/m-p/198598#M915) hi chris, 
if you use relations api, you may set properties field in your query. in this field you should set the names of the properties which values must be retrieved from the server. the argument should be a string in the following format: "propertyname1, propertyname2, , , propertynamen" , wher… i got it over the internet.

var args = array.prototype.slice.call(arguments); JavaScript *itself* has nothing built in for handling query string parameters. 


Code running in a (modern) browser you can use the [`URL` object](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) (which is part of the APIs provided by browsers to JS):





```
var url_string = "http://www.example.com/t.html?a=1&b=3&c=m2-m3-m4-m5"; //window.location.href
var url = new URL(url_string);
var c = url.searchParams.get("c");
console.log(c);
```









For older browsers (including Internet Explorer), you can use [this polyfill](https://github.com/ungap/url-search-params) or the code from the original version of this answer that predates `URL`:


You could access `location.search`, which would give you from the `?` character on to the end of the URL or the start of the fragment identifier (#foo), whichever comes first.


Then you can parse it with this:





```
function parse_query_string(query) {
  var vars = query.split("&");
  var query_string = {};
  for (var i = 0; i < vars.length; i++) {
    var pair = vars[i].split("=");
    var key = decodeURIComponent(pair[0]);
    var value = decodeURIComponent(pair[1]);
    // If first entry with this name
    if (typeof query_string[key]  "undefined") {
      query_string[key] = decodeURIComponent(value);
      // If second entry with this name
    } else if (typeof query_string[key]  "string") {
      var arr = [query_string[key], decodeURIComponent(value)];
      query_string[key] = arr;
      // If third or later entry with this name
    } else {
      query_string[key].push(decodeURIComponent(value));
    }
  }
  return query_string;
}

var query_string = "a=1&b=3&c=m2-m3-m4-m5";
var parsed_qs = parse_query_string(query_string);
console.log(parsed_qs.c);
```




You can get the query string from the URL of the current page with:



```
var query = window.location.search.substring(1);
var qs = parse_query_string(query);

``` Hello Dmytro,


You will need to bind to the Custom Command, create arguments for the command execution, specify parameter values that will be used to execute the command in the Scheduled Task and then pass the arguments to the Arguments property of the action. Here is the code that will do the trick:



```
# Define actions and conditions for the task

$commandID = "{a7264a61-b77d-4386-a138-ec2557c5b3ba}" # Command ID
$commandDN = "CN=MyCommand,CN=Custom Commands,CN=Configuration Objects,CN=Adaxes Configuration,CN=Adaxes" # Command DN

# Create action set
$actionsAndConditions = $task.ConditionedActions.Create()
$actionsAndConditions.ConditionsLogicalOperation = "ADM_LOGICALOPERATION_AND"
$actionsAndConditions.SetInfo()

# Create execute Custom Command action
$action = $actionsAndConditions.Actions.CreateEx("adm-CustomCommandAction")
$action.ExecutionOptions = "ADM_ACTIONEXECUTIONOPTIONS_SYNC"

# Get action
$removeAction = $action.GetAction()

# Bind to Custom Command
$customCommand = $Context.BindToObjectByDN($commandDN)

# Specify command arguments
$arguments = $customCommand.CreateArguments()
$arguments.SetParameterValue("MyParameter", "MyValue") # Parameter value

# Configure the action
$removeAction.CustomCommandId = $commandID
$removeAction.Arguments = $arguments

# Save action
$action.SetAction($removeAction)
$action.SetInfo()
```

In the script, the $commandDN variable specifies the distinguished name (DN) of the Custom Command. For information on how to get the DN of a directory object, see <http://adaxes.com/sdk/?HowDoI.GetDnOfObject.html>.


For details, have a look at the following SDK article: <http://adaxes.com/sdk/?IAdmCustomCommandAction2.html>. Copy Code

```
This is an example
```
  

C#Copy Code

```
public partial class Default2 : System.Web.UI.Page
{
    protected void Page\_Load(object sender, EventArgs e)
    {
        //calling your derived class
        MyClass objMyClass = new MyClass();
        objMyClass.DoSomthing();
    }
}
//Abstract Class
public abstract class MyAbstractClass
{
    public abstract void DoSomthing();
}
//derived class
public class MyClass:MyAbstractClass
{
    public MyClass()
    { }
    public override void DoSomthing()
    {
        //add your implimentation here
    }
}
```
  

  

[edit] added a small comment[/edit] [image] bryan:

you will need to hunt through the page and find the raw html dom object.

thank you. but i guess, it’s impossible to open select widget.

callback = customjs(args=dict(select\_=select),code="""

var el = document.getelementsbyname(select\_.name)[0];

… hello dror, - - you can inherit the ribbontab base class and add some custom elements to the children collection, - i have prepared a very small example, it should get you started: - - - using system; -     using system.drawing; -     using system.windows.forms; -     using telerik.wincontrols; -     using telerik.wincontrols.ui; -   -     public partial class radribbonform1 : telerik.wincontrols.ui.radribbonform -     { -         public radribbonform1() -         { -             initializecomponent(); -         } -   -         protected override void onload(eventargs e) -         { -             base.onload(e); -   -             var tabitem1 = new customribbontab(manage); -             var tabitem2 = new customribbontab(remove); -             radribbonbar1.commandtabs.addrange(new customribbontab[] { tabitem1, tabitem2 }); -         } -     } -   -     public class customribbontab : ribbontab -     { -         private radbuttonelement radbuttonelement; -   -         protected override type themeeffectivetype -         { -             get -             { -                 return typeof(tabitem); -             } -         } -   -         private timer focustimer; -   -         public customribbontab() -             : base() -         { -             createtimer(); -         } -   -         public customribbontab(string text) -             : base(text) -         { -             createtimer(); -         } -   -         private void createtimer() -         { -             this.focustimer = new timer { interval = 500 }; -             this.focustimer.tick += delegate -                 { -                     this.radbuttonelement.visibility = elementvisibility.collapsed; -                 }; -         } -   -         protected override void createchildelements() -         { -             base.createchildelements(); -   -             radbuttonelement = new radbuttonelement(x); -             radbuttonelement.size = new size(10, 10); -             radbuttonelement.minsize = new size(10, 10); -             radbuttonelement.maxsize = new size(10, 10); -             radbuttonelement.click += new eventhandler(radbuttonelement\_click); -             radbuttonelement.mouseenter += new eventhandler(radbuttonelement\_mouseenter); -             radbuttonelement.mouseleave += new eventhandler(radbuttonelement\_mouseleave); -             radbuttonelement.borderelement.visibility = elementvisibility.collapsed; -             radbuttonelement.visibility = elementvisibility.collapsed; -             this.children.add(radbuttonelement); -         } -   -         void radbuttonelement\_mouseleave(object sender, eventargs e) -         { -             this.onmouseleave(e); -         } -   -         void radbuttonelement\_mouseenter(object sender, eventargs e) -         { -             this.onmouseenter(e); -         } -   -         void radbuttonelement\_click(object sender, eventargs e) -         { -             ((telerik.wincontrols.ui.radtabstripelement)(this.parenttabstrip)).items.remove(this); -         } -   -         protected override void onmouseenter(eventargs e) -         { -             base.onmouseenter(e); -             focustimer.stop(); -             radbuttonelement.visibility = elementvisibility.visible; -         } -   -         protected override void onmouseleave(eventargs e) -         { -             base.onmouseleave(e); -             focustimer.start(); -         } -   -         protected override sizef arrangeoverride(sizef finalsize) -         { -             finalsize = new sizef(finalsize.width + this.children[3].desiredsize.width, finalsize.height); -             base.arrangeoverride(finalsize); -   -             this.children[3].arrange(new rectanglef( - (int)(finalsize.width - 1.7 * this.children[3].size.width), (finalsize.height / 2) - (this.children[3].desiredsize.height / 2 + 1), finalsize.width, this.children[3].desiredsize.height)); -   -             return finalsize; -         } -   -         protected override void disposemanagedresources() -         { -             radbuttonelement.click -= new eventhandler(radbuttonelement\_click); -             radbuttonelement.mouseenter -= new eventhandler(radbuttonelement\_mouseenter); -             radbuttonelement.mouseleave -= new eventhandler(radbuttonelement\_mouseleave); -   -             base.disposemanagedresources(); -         } -     } - - - please see the attached image if this is what you wanted. - - hope this helps, if you have any other questions or comments, please let me know, - - best regards, - emanuel varga use promise.allsettled(). the following code works, it's simply going to skip over the rejected promise:
```javascript
function getwikiprofiles(data) {
 const profiles = data.people.map(person => {
 return getjson(wikiurl + person.name);
 });
 return promise.allsettled(profiles);
}
function generatehtml(data) {
 //console.log(data);
 data.foreach(person => {
 if (person.status  'fulfilled') {
 person = person.value;
 const section = document.createelement('section');
 peoplelist.appendchild(section);
 section.innerhtml = 
 ![](%24%7bperson.thumbnail.source%7d)
${person.title}



${person.description}


${person.extract}


;
 }
 });
```