Ways to specifically select an element based on its type and class

I am struggling to create a vanilla JS function that will resize fonts in a container with a specified class. I came across this demo, which seemed promising. However, the 'Javascript' version uses the $() jquery selector to target elements, making it incompatible with vanilla JS.

Since vanilla JS does not support this method, I am unsure how to proceed with implementing the solution.

The complexity arises when I have multiple instances of the same element with the same class that need to be processed individually. For example, if I have two h3 elements with the '.resize' class, each with different dimensions, applying a generic solution would cause conflicts.

One approach I considered was using unique IDs for each element instead of the '.replace' class, then creating an array of these IDs to iterate over and target each element. However, this solution is neither elegant nor scalable.

I attempted to modify the function to target the .style.fontSize attribute exclusively within vanilla JS, but encountered an infinite loop issue.

JS:

function autoSize () {
  var el, elements, _i, _len, _results;
  elements = document.getElementsByClassName('resize');
  console.log(elements);
  if (elements.length < 0) {
    return;
  }
  _results = [];
  for (_i = 0, _len = elements.length; _i < _len; _i++) {
    el = elements[_i];
    _results.push((function(el) {
      var resizeText, _results1;
      resizeText = function() {
        var elOldFontSize = el.style.fontSize;
        var elNewFontSize;


        elNewFontSize = (parseInt(elOldFontSize.slice(0, -2)) - 1) + 'px';
        el.style.fontSize = elNewFontSize;
      };
      _results1 = [];
      while (el.scrollHeight > el.offsetHeight) {
        _results1.push(resizeText());
      }
      return _results1;
    })(el));
  }
  return _results;
}

Answer №1

In the world of Vanilla JS, some limitations exist; however, browser-flavored Vanilla JS has a solution. Introducing document.querySelector (learn more) and document.querySelectorAll (explore here).

Let's take a look at examples provided in the documentation:

In this instance, the function will return the first element with the class "myclass" within the document:

var el = document.querySelector(".myclass");

The following example showcases how to retrieve all div elements that have either the class "note" or "alert" within the document:

var matches = document.querySelectorAll("div.note, div.alert");

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

Explore various Lists with unique headings by applying filters or conducting searches

I am looking for a script that can filter and search various lists with the same class. The script should display the headings of the lists if there is at least one matching search name. If there are no matching search names, the heading of the list should ...

Is there a way to stop my <pre> code from being displayed on the page?

Currently, I am utilizing the google code prettifier found at http://code.google.com/p/google-code-prettify/ This tool functions similarly to stack overflow by enhancing and highlighting syntax when a block of code is input. However, I have encountered a ...

Combining Arrays in AngularJS with an owl-carousel Setting

My goal is to implement an endless scrolling carousel in AngularJS using owl-carousel. The idea is to load new items every time the carousel is fully scrolled and seamlessly merge queried elements with the existing list. However, I've encountered a pr ...

Tips for correctly implementing JavaScript conditional statements

Upon running this jQuery (1.8.3) code, I consistently receive the "in" alert message even when the length is greater than 1. The purpose of my actions is to dynamically add elements to a menu while ensuring that the element does not already exist. Even a ...

Troubleshooting: ng-disabled not function properly in Angular.js

My goal is to only allow the button to be enabled if there is text in the textfield, but for some reason I am unable to make ng-disabled work: <form novalidate> <button type="submit" ng-click="add('+')" ng-disabled="bittext.$invalid ...

Locate and eliminate all occurrences of "<br />" within a webpage using jQuery

I am currently working on a project using the Cargo Collective platform and I have noticed that it automatically includes unnecessary <br /> tags in the body of my document. Is there a way to use jQuery to scan for all instances of <br /> tags ...

Is it possible to access a function on the main page from a plugin?

In my plugin, I need to call a function that is located on the main page, not within the plugin's .js file. EDIT I am currently working with jQuery to parse a very large XML file and generate a substantial list (resulting in a 1.1 MB HTML file when ...

Tips for featuring the latest blog post at the top of a NextJS blog

I have a website built on Next JS with a blog page. The setup is correct, where the /blog page displays content based on slugs. Currently, new blog posts are appearing at the bottom of the page, under older ones. I want to reverse this so that when a new p ...

Preventing Content Changes When Ajax Request Fails: Tips for Error Checking

I was struggling to find the right words for my question -- My issue involves a basic ajax request triggered by a checkbox that sends data to a database. I want to prevent the checkbox from changing if the ajax request fails. Currently, when the request ...

What is the best way to incorporate a dynamic background in NextJS using Tailwind?

I have a poster image that I want to use as a background image, fetched from MovieDb. I tried putting it inside the className like this: className={bg-[url('${path}')] h-screen bg-cover bg-center text-white border-b-8 border-b-solid border-b-sla ...

What is the best way to instantly validate a form in React before submitting?

Having trouble with my form validation. The issue is that after validating the form on submit, I have to click the submit button a second time to actually send it and see the console.log at the bottom of the file. Any ideas on what might be causing this a ...

Extract the directory name from a URL using PHP, excluding any file names or extensions

Can anyone guide me on extracting the folder name only from a URL in PHP? For example, if my URL is I'm interested in retrieving just the part of the URL. Any suggestions on how to achieve this would be much appreciated. Thanks! ...

The two items are not situated side by side

Trying to make my page responsive, but when I inspect and look into mobile view, the elements do not align next to each other like they do on desktop. https://i.sstatic.net/8WhxD.png I want the shopping cart icon and button to be positioned next to each o ...

Is there a way to show output on render rather than using console.log in node.js?

I have successfully sorted the objects as shown in the link below. My next challenge is to integrate the sorted object into my render function rather than just using console.log(). I'm uncertain if converting it back into an object is the right appro ...

How can I trigger a JavaScript function when the ENTER key is pressed?

I'm attempting to use JavaScript to scroll down a page. The code below works perfectly when I use javascript:pageScroll() in a link or button: <SCRIPT LANGUAGE="Javascript"> function pageScroll() { window.scrollBy(0,50); // hor ...

Navigating to a new page once a backend function in Express has finished executing

Recently, I have been experimenting with express web servers to create a website that allows users to sign in using Discord's OAuth2 API. In order to secure sensitive information, I have been utilizing the express-session npm module to store data with ...

Checking for at least one matching pair in a JavaScript object

I have a pair of dictionaries that I need to compare in JavaScript. The goal is to determine if there is at least one identical key-value pair between them, not necessarily the entire dictionary being identical. my_dict = {"Text1":"Text1", "Text2":"Text3", ...

Using jQuery UI Dialog with pjax for dynamic content loading

I'm currently utilizing pjax within a web application that incorporates jQuery UI dialogs. One issue I've encountered is that the div element responsible for creating the dialog gets displaced from its original container in the DOM once the dialo ...

Retrieve all populated fields on the second tier using Node.js and Mongoose

Do you have any insights to share on Node.js and mongoose? I've defined a mongoose schema and when I use findOne(), it returns a document with multiple elements under the "resource" key. Below is an example of how the document looks like: { "met ...

Trigger event when user ceases to click

I have successfully implemented a click event using jQuery. Here is the code: $('#myButton').click(function(){ // perform desired actions }); However, I am facing an issue where multiple intermediate events are triggered if the user clicks on ...