Html Agility Pack Get All Elements by Class

Html Agility Pack is a power tool for parsing through document source. I had a need where I needed to parse a document using html agility pack to get all elements by class name. It really is a simple function with Html Agility Pack but getting the syntax right was the difficult part for me.

Here is my use case:

I need to select all elements that have the class float on them. I started with this query which was working for just div tags.

var findclasses = _doc.DocumentNode.Descendants("div").Where(d => 
    d.Attributes.Contains("class") && d.Attributes["class"].Contains("float")
);

What this does is it takes your _doc and finds all divs within where they have an attribute names class and then goes one step farther to ensure that class contains float

Whew what a mouth full. Lets look at what an example node it would select.

<div class="className float anotherclassName">
</div>

So now, how do we get ALL ELEMENTS in the doc that contain the same class of float. If we take a look back at our HTML Agility Pack query there is one small change we can make to the .Descendants portion that will return all elements by class. This may seem simple, but took quite awhile to come to, if you simply leave .Descendants empty, it will return all elements. Look below:

var findclasses = _doc.DocumentNode.Descendants().Where(d => 
    d.Attributes.Contains("class") && d.Attributes["class"].Contains("float")
);

The query above will return ALL ELEMENTS that include a class with the name of float.

Documented based off my question on stackoverflow here: Html Agility Pack get all elements by class

HTML CSS Progress Bar

Simple HTML CSS Progress Bar Using Squares with JSFiddle

It took awhile to come across a progress bar that was light and had rounded sections like I wanted. I created a progress bar that is mainly HTML and CSS except for updating the width using JavaScript. The concept is quite simple, we overlay however many squares we want with a background div for the progress meter. Lets take a look at the HTML markup for this.

<div class="Progressbar">
    <div class="ProgressbarMeter"></div>
    <div class="InnerDivs"></div>
    <div class="InnerDivs"></div>
    <div class="InnerDivs"></div>
    <div class="InnerDivs"></div>
    <div class="InnerDivs"></div>
</div>

Its really simple, we have a containing div that holds it all together and controls the main width for the progress bar. Inside Progressbar we have 6 divs total; 1 div is the progress meter bar and the other 5 are the div overlays for the squares.

Now for the CSS portion.

.Progressbar {
    background-color: #d7d7d7;
    width: 110px;
    margin-top: 1px;
    position: relative;
    height: 41px;
    border-radius: 3px;
}
.ProgressbarMeter {
    background-color: #669900;
    width: 40%; /*This controls the green progress bar.*/
    margin-top: 1px;
    height: 40px;
    border-radius: 3px;
    position: absolute;
}
.InnerDivs {
    border: 1px solid black;
    width: 20px;
    height: 40px;
    border-radius: 3px;
    float: left;
    position:relative;
}

The only item really to take note of within the CSS is the width under ProgressbarMeter. This controls the width of the progress bar.

Here is a quick image of what it looks like.

HTML CSS Progress Bar

HTML CSS Progress Bar

JSFIDDLE Link to the above progress bar example: JsFiddle HTML CSS Progress Bar

Create Custom KnockoutJS Binding For Enter Key Press

Today I had to add an event to an input box that when the user hits enter on the keyboard, it would call a JavaScript function. However, it’s pretty easy to do with a onkeypress=”” but it still uses a lot of other JavaScript and jQuery. I wanted to do this with using a custom KnockoutJS binding for the enter key so lets take a look at the mark up first.

//Field for typing. enterKey is the name of the custom binding.
<input id="name" data-bind="value: name, enterKey: addName" /> 

//This is the button for if they click instead of enter.
<input id="addName" type="button" data-bind="click: addName" value="Add" /> 

Take notice that in the first line and in the second like they are both pointing to the same function addName. Now lets take a look at the custom binding called enterKey.

// Custom Binding
ko.bindingHandlers.enterKey = {
  init: function (element, valueAccessor, allBindings, data, context) {
    var wrapper = function (data, event) {
      if (event.keyCode === 13) {
        valueAccessor().call(this, data, event);
      }
    };
    ko.applyBindingsToNode(element, { event: { keyup: wrapper } }, context);
  }
};

The cool thing about this customer knockoutjs binding is that you could pass it any function to call. All you would have to do in the markup is data-bind="enterKey: aDifferentFunction" and it would work the same. This obviously works great if you have multiple instances where you would like to check the enter key press and do a certain function without having to do a ton of checking of what’s calling what.

This was answered by Dennis on StackOverflow when I asked how to convert javascript onkeypress to knockoutjs to call on enter.

How to find an element in an observable array in KnockoutJS

How to find an element in an observable array in KnockoutJS is not that hard of a task.  This is assuming that the two items you are comparing are a reference to the same item.  This is more of a custom comparison function to compare a value in an array to some other value.  To complete this we will use the ko.utils.arrayFirst from KnockoutJs.

Take a look at the following Javascript:

var match = ko.utils.arrayFirst(myObservableArray(), function(item) {
    return someValue.name === item.name;
});

Essentially what is happening here is that knockout is combing through the myObservableArray and looking for a match on name. If it finds a match then it returns that object as match. (Just wait, it’ll make sense). If it doesn’t find anything, then match is returned as undefined.

Here is the second part that deals with the match logic:

if (!match) {
  myObservableArray.push(someValue);
}

If match has a value to it and you apply the ! operator the outcome is false.

If match is undefined and you apply the ! operator the outcome is true.

So overall all, if our someValue does not exist in our myObservableArray, then we add it.


Error Messaging Using KnockoutJS Observable Applying CSS

When doing error messages in an application I like to use KnockoutJS Observable to apply a css class to an input box to color it red meaning it’s required. The concept is quite simple really. You have an observable for the field.

self.FirstNameValidation = ko.observable('');

The point is when your validation fails, you add a message to the observable.

if(self.FirstName() == ''){
      self.FirstNameValidation('First Name Is Required');
}

So now that we have our observable set with an error message we can add a data-bind event to the input box to apply a css class to it.

<input id="firstName" data-bind="value: FirstName, css: { 'validationerror': FirstNameValidation() }">

Looking at the example above, the css class ‘validationerror’ will be added to the input box if there is a value in FirstNameValidation(). Simple way to add a visual cue to an input element that something is missing.

StackOverflow Profile