Place attribute value directly under the border of an HTML element using a combination of JavaScript and CSS

I'm currently working on a JavaScript script to scan the DOM for elements that have a specific custom attribute called example-type. The goal is to apply CSS styling to draw a border around these elements and then display the value of the example-type attribute right below the button element, snug against the border.

The challenge I'm facing is figuring out how to use CSS to position the text against the border without pushing down neighboring elements or causing any layout issues.

<button example-type="hello" example-thing="world" example-name="alice">
  Button
</button><br>

<a href="www.google.com"class="centered" example-type="link">search</a>
<br>
<a href="testing.com"class="centered">test</a>


var el = document.querySelectorAll('[example-type]')

for (var i = 0; i < el.length; i++) {
    el[i].setAttribute("style","border:1px; border-style:solid; border-color:#FF0000;")
  var exampleTypeValue = el[i].getAttribute("example-type")
  //add value right below the border of the element 
}

I have successfully added the red border around the elements and retrieved the values, but struggling with formatting them to look like this:

Take note of the red box with white text positioned just below the border

https://i.sstatic.net/3XR1X.png

Answer №1

To add spacing around an element, utilize the padding attribute.

CSS padding properties create room around the content of an element within its borders.

Here's an example of the code you can implement:

el[i].setAttribute("style","border:1px; border-style:solid; border-color:#FF0000;padding:10px")

Answer №2

To accomplish this task, I have utilized absolute divs in the following manner.

var elements = document.querySelectorAll('[example-type]')

for (var index = 0; index < elements.length; index++) {

  elements[index].classList.add("borderBox");

  var exampleTypeValue = elements[index].getAttribute("example-type")
  var newDiv = document.createElement("div");
  newDiv.innerHTML = exampleTypeValue;
  newDiv.style.top = elements[index].offsetTop + elements[index].offsetHeight + "px";
  newDiv.style.left = elements[index].offsetLeft + "px";
  newDiv.classList.add("absDiv")

  document.getElementsByTagName('body')[0].appendChild(newDiv);
  //position the element right below the border 
}
.borderBox {
  border: 1px;
  border-style: solid;
  border-color: #FF0000;
  margin: 15px;
}

.absDiv {
  position: absolute;
  display: block;
  font-size: 10px;
  color: #fff;
  background: red;
}
<button example-type="hello" example-thing="world" example-name="alice">
  Button
</button>

<a href="www.google.com" class="centered" example-type="link">search</a>

<a href="testing.com" class="centered">test</a>

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

The VueJS component from a third-party source is not located in the node_modules directory

Utilizing vue-cli version 3 for a fresh vuejs project (I've been dedicating ample time to learning vuejs, but this marks my initial attempt at integrating a third-party component). I'm aiming to incorporate a visually appealing grid component. Th ...

What is the process for binding an absolute path instead of a relative path in a script that includes Node and Perl calls?

In my script, there is a function with the following code: def tokenize(latex,kind='normalize'): output_file = './out.lst' input_file = './input_file.lst' cmd = "perl -pe 's|hskip(.*?)(cm\\|in& ...

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 ...

Is there a way to customize the color of a MUI styled component?

I have a customized MUI component that displays a circular badge in green. const StyledGreenBadge = styled(Badge)(({ theme }) => ({ '& .MuiBadge-badge': { backgroundColor: '#44b700', color: '#44b700', ...

Achieving consistent spacing between elements within a column in Bootstrap 5

Picture a bootstrap column filled with various elements such as divs, paragraphs, and links. How can I evenly space these elements inside the column without using margins or padding? I am looking for an automatic way for the elements to be spaced equally a ...

Tips on safeguarding your templates while working with SailsJS and AngularJS

I am currently working on a web application using SailsJS and AngularJS. My project requires session management to track user login status. I came across this helpful tutorial and implemented an index.ejs view located in the /view folder. Within the index. ...

Switching image sources depending on CSS prefers-color-scheme: A guide

In my endeavor to incorporate the latest CSS prefers-color-scheme media query into my website, I encountered a challenge. I have an img (image) element featuring a very dark blue image, which clashes poorly with the new dark mode setting. Is there a simpl ...

Tsyringe - Utilizing Dependency Injection with Multiple Constructors

Hey there, how's everyone doing today? I'm venturing into something new and different, stepping slightly away from the usual concept but aiming to accomplish my goal in a more refined manner. Currently, I am utilizing a repository pattern and l ...

Filtered Owl Carousel

Hello everyone. Just wanted to mention that our English may not be perfect. I managed to filter with owl carousel by tweaking some codes I found online. It's working now, but I'd love for it to have an animated effect while filtering, like a fad ...

rearranging nodes from multiple arrays into a single array and then repositioning them within the parent array using angularjs

[![enter image description here][1]][1]I am working with AngularJS and I have multiple arrays named list1, list2, and list3. Each array is used in a different list. Within my application, there are two buttons and two divs - the left div displays elements ...

Interacting with API through AngularJS $http.get

I am a beginner in AngularJS and I am trying to grasp its concepts by studying example codes. Currently, I have found an interesting code snippet that involves the $http.get function. You can find it here: I attempted to replace the URL with my own, but ...

React JS routes function properly only upon being reloaded

Encountering a problem with my reactJS routes where the URL changes in the address bar when clicking on a link, but the component does not render unless I refresh the page. Here is an excerpt from my code: index.js import React, { Component } from &apos ...

Angular rest call is returning an undefined response object attribute

When attempting to retrieve the attribute of a response object, it is returning as "undefined". var app = angular.module('angularjs-starter', []); app.controller('MainCtrl', function($scope, $http) { $scope.addNewChoice = functio ...

Is there a way for me to establish a maximum word count for a paragraph?

When my paragraphs get lengthy, I only want the first 30 words to display on two lines. Is there a way to achieve this using HTML, CSS, or JS? The code snippet I tried did not work as expected. .long-text{ width: 70ch; overflow: hidden; white-sp ...

Transform them into async/await in JavaScript

Exploring the promise-retry library, I discovered the following syntax: promiseRetry(function (retry, number) { return doSomething() .catch(retry); }) .then(function (value) { // .. }, function (err) { // .. }); Since I am utilizing a ...

In the world of NodeJS, the 'Decimal' module functions just as effectively when written as 'decimal'

I recently installed and started using the package decimal.js in my NodeJS project. If you're interested, you can find more information on this package here. What I found interesting is that while all the examples recommend using Decimal, I also not ...

Adding an image to a server through PHP in the TinyMCE editor

Currently, I am in the process of utilizing TinyMCE text editor for uploading images using PHP and JS database. However, I find myself perplexed when it comes to sending the image to the server. Below is the snippet of the JS code being used: <script ...

Obtaining and transferring identifiers for jQuery code execution

My goal is to create a script that dynamically changes the content of a webpage using a foreach array. The HTML structure I am working with looks like this: <div id="bigleftproject"> <p>content to be replaced</p> </div> <div ...

Order comments based on their category using vue.js

I have a component form with select filter: <template> <div class="form-group"> <select name="" v-model="filterRev" @change="filterReviews(filterRev)" class="form-control" id=""> <option ...

Is there a way to eliminate unnecessary chunks from MUI in NextJS?

https://i.sstatic.net/zAkV0.png I recently created a single page and noticed that there is a significant amount of unused JavaScript in my codebase. Specifically, I am using MUI and React icons. Any suggestions on how to efficiently manage this issue? T ...