-1

I'm trying to replace an older combination of bootstrap, jQuery with bootstrap version 5.0 (and vanilla JavaScript). The HTML remains unchanged:

        <div class="col-xl-5 col-lg-5 col-md-5 col-sm-11 card">
          <p style="text-align:center; font-weight:bold; ; font-size:1.1em;">Raw Data Preview</p>
          <div id="lv_container" class="od-server l-image">
            <img class="whatever" name="lv_name" id='lv_image' src='/api/0.1/l_v/image' data-src='/api/0.1/l_v/image' load="resizeImage()">
          </div>
        </div>

Combining a standard jQuery selector:

    img_elem = $('#lv_image');

I reuse img_elem in other functions:

// Example 1:
img_elem.attr("src", img_elem.attr("data-src") + '?' +  new Date().getTime());
// Example 2:
var img_width = img_elem.naturalWidth();
var img_height = img_elem.naturalHeight();
var img_container_width =  $("#lv_container").width();
var img_container_height = $("#lv_container").height();
// Example 3:
img_elem.width( Math.floor(img_scaling * img_width));
img_elem.height(Math.floor(img_scaling * img_height));

Because img_elem is an [object Object] (i.e. a string version of object instance), I thought I could just find a vanilla JavaScript way of obtaining the same object. But however I try using document.getElement... and document.querySelector, I only get HTMLImageElement, HTMLCollection or NodeList objects. Syntax for these attempts:

    let a = document.getElementById('lv_image');
    console.log("a: " + a + " " + typeof a);
    let b = document.querySelector('#lv_image');
    console.log("b: " + b + " " + typeof b);
    let c = document.getElementsByClassName('whatever');
    console.log("c: " + c + " " + typeof c);
    let d = document.getElementsByName('lv_name');
    console.log("d: " + d + " " + typeof d);

Web development is not my expertise, I must be missing an obvious term here. How do I obtain the equivalent vanilla JavaScript object or functionality? Is jQuery really so radically different that there is no joint solution for this and I need to find a separate solutions for Example 1, Example 2 and Example 3?

-- Edit1 --

Part of my confusion is/was, understanding the syntax of JavaScript/jQuery. I was puzzled that the jQuery API didn't document the naturalWidth(), naturalHeight() functions. The reason for this is, my inherited code contained the following functionality:

var
props = ['Width', 'Height'],
prop;

while (prop = props.pop()) {
    (function (natural, prop) {
        $.fn[natural] = (natural in new Image()) ?
        function () {
            return this[0][natural];
        } :
        function () {
            var
            node = this[0],
            img,
            value;

            if (node.tagName.toLowerCase() === 'img') {
                img = new Image();
                img.src = node.src,
                value = img[prop];
            }
            return value;
        };
    }('natural' + prop, prop.toLowerCase()));
}

For clarity, this is a function definition for those two functions.

8
  • 1
    "Because img_elem is an [object Object] (i.e. a string version of object instance), I thought I could just find a vanilla JavaScript way of obtaining the same object." - it is not any old plain object instance, it is an instance of jQuery. And asking how to get an instance of jQuery without using jQuery ... well that doesn't make the most sense to begin with. Commented Mar 15, 2022 at 10:42
  • 1
    Using any DOM methods such as getElementById or similar, will eventually get you an HTMLImageElement here. And if you go check what properties that provides, you should find everything that you need to create the equivalent version of your three examples above using native code. Commented Mar 15, 2022 at 10:45
  • Except for .attr("data-src"), that is not image specific. How to access custom data attributes using native JS - developer.mozilla.org/en-US/docs/Learn/HTML/Howto/… Commented Mar 15, 2022 at 10:47
  • img_elem = $('#lv_image'); gives you a jQuery wrapper around a DOM element (assuming there is one with id="lv_image"). a = document.getElementById('lv_image'); gives you the DOM element directly (again, assuming there is one). That's a good first step. Then you need to look how to do the things jQuery's methods do using the nativ DOM. For instance, instead of .attr("src", value) you'd use .setAttribute("src", value) (or, for that specific one, .src = value;). MDN has excellent DOM reference information here. Commented Mar 15, 2022 at 10:48
  • And jQuery's width()/ height() methods would set those in CSS, not directly manipulate the _attributes_of the image. But manipulating element styles in JS is a common topic, easy enough to research. Commented Mar 15, 2022 at 10:50

1 Answer 1

0

Replacing the standard jQuery selector, by calling the getElementById() we obtain an Element object describing the DOM element object in question.

var image_element = document.getElementById('lv_image');

Addressing Example 1: Accessing and modifying attributes is carried out using the .getAttribute() and .setAttribute() functions

var img_new = document.getElementById('lv_image');
var data_src = img_new.getAttribute('data-src');
img_new.setAttribute("src",
    data_src + '?' + new Date().getTime()
);

Addressing Example 2, first half: Dealing with 'natural' dimensions - these are straightforwardly available through the API:

var image_element = document.getElementById('lv_image');
var img_height = image_element.naturalHeight;
var img_width = image_element.naturalWidth;

Addressing Example 2, second-half: I couldn't work out how to access the computed dimensions, so I had to introduce a clutch by subtracting the appropriate padding from the corresponding width/height. In my code, the borders are 0 so I ignored them (they are apparently "0px none rgb(...)").

    const lv_container = document.getElementById('lv_container');
    const cssObj = window.getComputedStyle(lv_container, null);

    const padding = cssObj.getPropertyValue("padding");
    // Turn "40px 15px" string into tokens
    const padding_tokens = padding.match(/\d+/g);
    // Multiply by 2 because padding on both sides
    const width_padding = padding_tokens[1] * 2;
    const height_padding = padding_tokens[0] * 2;

    const img_container_width = lv_container.offsetWidth - width_padding;
    const img_container_height = lv_container.offsetHeight - height_padding;

Addressing Example 3, through the .querySelector() function (which return HTMLImageElement - see [a]) the width and height can be modified:

document.querySelector('#lv_image').width = Math.floor(img_scaling * img_width);
document.querySelector('#lv_image').height = Math.floor(img_scaling * img_height)

[a] - https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/height A useful comparison between JavaScript and jQuery: http://www.lucemorker.com/blog/javascript-vs-jquery-quick-overview-and-comparison

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.