Obtain the height of the div element class

Is it possible to retrieve the height of a class in C#? I am currently utilizing HTMLAgilityPack to access the nodes. Here is my current code.

private async void GetCldInfos()
    {
        string sURL = @"https://m.investing.com/economic-calendar/";
        using (HttpClient clientduplicate = new HttpClient())
        {
            clientduplicate.DefaultRequestHeaders.Add("User-Agent",
                "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident / 6.0)");

            using (HttpResponseMessage responseduplicate = await clientduplicate.GetAsync(sURL))
            using (HttpContent contentduplicate = responseduplicate.Content)
            {
                try
                {
                    string resultduplicate = await contentduplicate.ReadAsStringAsync();

                    var websiteduplicate = new HtmlDocument();
                    websiteduplicate.LoadHtml(resultduplicate);
                    var News = websiteduplicate.DocumentNode.Descendants("div").Where(o => o.GetAttributeValue("class", "") == "js-economic-calendar").Single();
                    //get height here
                }
                catch (Exception ex1)
                {
                    throw ex1.InnerException;
                }
            }
        }
    }

Edit: an image can be found here: https://i.sstatic.net/DN8AL.png In the image, I am struggling to determine its height. Is there a way to obtain this height programmatically? My intention is to incorporate it into a scroll viewer. I have disabled the browser's scroll bars so that I can utilize my own. Therefore, I need to adjust the scroll viewer's height to correspond with the form...

Answer №1

This tutorial demonstrates how to use the headless browser Watin to extract the height of a DOM element by employing inline JavaScript.

To begin, you need to install Watin through Visual Studio's Nuget Package Manager Console with the following command:

PM> Install-Package WatiN

Once Watin has been successfully installed, follow this script to navigate to a webpage and execute a simple JavaScript snippet to fetch the height of an element:

using WatiN.Core;
...

private void buttonGetElementHeight_Click(object sender, EventArgs e)
{
    WatiN.Core.Settings.Instance.MakeNewIeInstanceVisible = false;
    IE browser = new IE();

    browser.GoToNoWait("https://m.investing.com/economic-calendar/");
    browser.WaitUntilContainsText("Filters");

    var height = browser.Eval("document.getElementsByClassName('js-economic-calendar')[0].offsetHeight");
    labelResult.Text = String.Format("Element height is {0}px", height);

    browser.ForceClose();
}

Additionally, a screenshot was captured to showcase the functioning button that retrieves the height:

https://i.sstatic.net/FFoWr.gif

NOTE

Keep in mind that this example serves as a test, so it is advisable to implement error handling for both C# Watin objects and any inline JavaScript being evaluated in the code.

ALTERNATIVE METHOD

If you prefer using Windows.UI.Xaml.Controls.WebView, here's how you can achieve the same outcome:

private async void webView1_LoadCompleted(object sender, NavigationEventArgs e)
{
    var offsetHeight = await webView1.InvokeScriptAsync("eval", new string[] {
        "document.getElementsByClassName('js-economic-calendar')[0].offsetHeight.toString()"
    });
    textBox.Text = offsetHeight;
}

private async void button_Click(object sender, RoutedEventArgs e)
{
    webView1.LoadCompleted += webView1_LoadCompleted;
    webView1.Navigate(new Uri("https://m.investing.com/economic-calendar/"));
}

A snapshot demonstrating the successful execution of this alternative approach:

https://i.sstatic.net/hoxfl.gif

Answer №2

It doesn't seem possible because the browser calculates the height.

In order to achieve this, you'll need to pre-render the HTML and then calculate it.


Update: If you're open to using JavaScript to obtain the height, it can be done easily.

Simply select the div wrapping the view for your slimscroll:


function getsize() {
    var el = $('#divIdYouWantSize'),
        curHeight = el.height(),
        autoHeight = el.css('height', $(window).height()).height();
            
    el.height(curHeight).animate({ height: autoHeight }, 100);
};

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

Is it possible to override the body width setting?

Is it possible to override the width of the body element? For example, consider the following: <body> <table id="table1"> <tr><td></td></tr> </table> <table id="table2"> <tr><td></td>& ...

When viewing the material-ui Chip component at normal zoom, a border outlines the element, but this border disappears when zoomed in or out, regardless of

Edit I have recently discovered a solution to the unusual problem I was facing with the material-ui Chip Component. By adding the line -webkit-appearance: none; to the root div for the Chip, the issue seems to resolve itself. However, this line is being a ...

Tips for retrieving formatted text layout from the database

I recently encountered an issue when adding text to my MySQL database using a textarea. The format of the text, including newlines and spaces, was saved in the database but not displayed as such when viewed directly. When I retrieve this string from the da ...

Switch between various div elements

Looking for a way to toggle between different divs? Here's the scenario: You have a sidebar with a set of buttons. Upon entering the page, you only want the div containing the button group to be visible. However, when a specific button (e.g. Info) is ...

If the database row cannot be found, show a blank input page for error handling

There is an account settings page where users can submit a video and give it a title to display on their profile. Once submitted, the video is linked to the AccountInfoID and a new row is created in the dbo.Spotlight database: https://i.sstatic.net/f2Z0A. ...

Dynamic resizing in NextJs does not trigger a re-render

My goal is to dynamically pass the width value to a component's styles. Everything works fine on initial load, but when I resize the window, the component fails to re-render even though the hook is functioning as intended. I came across some informat ...

Using `ITimeouts.ImplicitlyWait(TimeSpan)` in Selenium is now considered outdated and deprecated

In my C# project, I have been using the ImplicitlyWait method like so: driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(20)); Initially, everything worked fine. However, after updating to selenium-dotnet-3.1.0, I encountered the following e ...

The code encountered an error because it was unable to access the property 'style' of an undefined element on line 13 of the script

Why is it not recognizing styles and showing an error? All paths seem correct, styles and scripts are connected, but it's either not reading them at all (styles) or displaying an error. Here is the html, javascript, css code. How can this error be fix ...

Steps for incorporating code to calculate the total price and append it to the orderMessage

I am seeking help with this program that my professor assigned to me. The instructions marked by "//" are the ones I need to implement in the code, but I'm struggling to understand how to proceed. Any assistance would be greatly appreciated, even just ...

How can I use CSS to transform a "+" symbol to an "x"?

When I created an accordion using HTML, JS, and CSS, I encountered a problem. The "+" sign in the accordion does not rotate correctly as it should. Instead of rotating from the middle of the "+" sign, it rotates from the top. This is my HTML code: <di ...

IE9 is not recognizing CSS styles

Why are my CSS styles not working in IE 9 but they work in IE 8 and Chrome? In the code snippet below, the style cpHeader is defined in a separate CSS file. Any ideas on why IE 9 is failing to render the styles properly? <asp:Content ID="Content2" Cont ...

New to Jquery - Experiencing difficulties with menu animation

I've encountered a strange problem that I've been struggling to find a solution for, even after spending hours trying to Google it... The animation on 'mouseenter' and 'mouseleave' is working perfectly fine. However, the issu ...

Styling with CSS and Angular: Loading background images dynamically with a greyscale effect

Incorporating the image displayed above as a background photo in CSS is my current objective using Angular. My aim is to alter the photo path for each new item added to my list. As it stands, the styles are hardcoded, resulting in a constant image that fun ...

Trigger an Onclick Event in Selenium

I am attempting to click on a menu icon with the following HTML code <a href="#" class="ctm-icon-link" onclick="show_menu('doc_107094', 1); return false;"><i class="icon-left-space icon-chevron-sign-down">&nbsp;</i></a& ...

Dynamic Font Formatting in Rails Table Based on Conditions

I need to customize the font color of dynamic values based on the state_id. If incident.state_id = 1, the font should be red; if incident.state_id = 2, it should be yellow; and if incident.state_id = 3, it should be green. incident.state_id = 1 : state.na ...

Troubleshooting JavaScript for Sidebar Disappearance due to marginRight and display CSS Issue

I need to adjust the layout of my website so that the sidebar disappears when the window is resized below a certain width, and then reappears when the window is expanded. Here is the HTML code: <style type="text/css"> #sidebar{ width:290 ...

Is there a more efficient method than continually deserializing and serializing data during API calls?

During the development of a website and its API to provide data, I have discovered that my current workflow involves redundant serialization and deserialization of the same data with every API call. Is there a more efficient approach I could take? Both the ...

What are some ways to incorporate Chakra UI with the after pseudo-class to generate a dark overlay in my video's foreground? (Specifically in the Hero section)

I am working on creating a layer effect in front of a video using Next.js and Chakra UI. I have provided an example in Figma: https://i.sstatic.net/aqIHk.png Here is the code snippet: function Hero() { const videoRef = useRef(); useEffect(() =& ...

Can CSS be used to consistently position content in a specific manner?

I previously inquired about a similar issue and received an excellent solution. Here is my jsbin http://jsbin.com/nuwagibayo/1/edit?html,css,output where I encountered the following scenario: The positioning of 12.50 seems slightly awkward in its current ...

What could be the reason that the accordion is failing to expand or collapse when clicked?

I am facing an issue where the div is not expanding or collapsing upon clicking the + sign. I have tried removing unnecessary scripts but it still doesn't work. Additionally, there is an error in the console: Uncaught TypeError: $(...).slideReveal is ...