What is the process for choosing an element, wrapping it in a <div>, and appending a class to it using only JavaScript?

When constructing a responsive website, all CMS entries are in markdown. It's not feasible to manually code the div into each new entry, so dynamic class addition is necessary.

The task at hand involves selecting an <img> within a post and wrapping it with a specific classed div for styling purposes. Otherwise, the original image width disrupts the layout.

After some trial and error, I discovered a solution by embedding a div around the image:

HTML

<div class="imgWrap">
  <img>
</div>


CSS

.imgWrap { 
  margin: 0 auto 18px;
  width: 100%; 
}

.imgWrap img { 
  max-width: 96%; 
}

However, the process needs to occur dynamically. My attempt using JavaScript was as follows:

<script>
  var x=document.getElementsByTagName('div.post img')[0];
  document.write("<div class='imgWrap'>");
  document.write("<img>");
  document.write("</div>");
</script>

In my search for answers, I came across resources like Javascript - How to add div class to createElement which led me to links such as HTML DOM className Property. While these provided some insight, I'm still puzzled about the next steps.

This site is being developed using Ruby with Jekyll. If you have any alternative strategies for tackling this issue, please share your suggestions!

Answer №1

const image = document.querySelector('div.post img');
const wrapper = document.createElement('div');
wrapper.className = 'imgWrap';
image.parentNode.insertBefore(wrapper, image);
wrapper.appendChild(image);

This code snippet should be effective for your needs as it utilizes the querySelector method which is compatible all the way back to IE8.

Check out this example on JSFiddle

If there are multiple instances of <img> tags that need to be manipulated, you can use document.querySelectorAll to select them all and then iterate through each one:

const images = document.querySelectorAll('div.post img');
for ( let i = 0, len = images.length; i < len; ++i ) {
    const img = images[i];
    const div = document.createElement('div');
    div.className = 'imgWrap';
    img.parentNode.insertBefore(div, img);
    div.appendChild(img);
}

Answer №2

Here is a simple method you can use:

const image = document.querySelector('div.post img');
const parent = image.parentNode;
const newDiv = document.createElement('div');
newDiv.className = 'imageContainer';
newDiv.appendChild(image);
parent.appendChild(newDiv);

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

toggle visibility of a div using AngularJS

Struggling to hide/show a div using AngularJS, I have gone through multiple tutorials with no success. Finally opted for the code snippet mentioned in this link, but still facing issues. Can anyone assist me in identifying the problem? PS: Using angular ...

Exploring the connections among nodes in a Force-Directed Graph using D3.js JavaScript

I am currently working on a complex graph that consists of around 150 nodes using D3 Javascript. The concept behind it is quite intriguing: Each node is interconnected with 100 other nodes. Out of these 100 nodes, 49 are further linked to another set of ...

Guide on creating rsa key pair on the client side with angular2

Is there a way to generate an 'rsa' key-pair on the client-side using angular2? I am looking to create a private/public key pair and store the private key in a database while using the public key on the client side. How can this be achieved? I c ...

Beginning the phone application using either HTML5 or Cordova

Is there a way to use either HTML5 or Cordova (PhoneGap) to initiate a call to a phone number? I am looking to create a button that says "Call 555-555-5555", and when clicked, it opens the phone app on the device with that specific number. ...

Is there a way to download and store the PDF file created using html2pdf in Node.js on my local machine?

I have successfully generated a PDF using html2pdf, but now I want to either send it to my server in Node.js or save it directly onto the server. Currently, the PDF is downloaded at the client's specified path, but I also need a copy saved on my serve ...

After toggling the switch to send the current state to the server, the React state remained unchanged

Could you clarify why the relay1 state is being sent as false? Why doesn't handleControlRelay1 change the state? Am I making a mistake by placing this inside a function? setRelay1((prevValue) => !prevValue); // ... const [relaysData, setRelaysD ...

What is the best way to handle texture loading delays in Three.js when using a JSON model?

Currently, I have successfully loaded a JSON model based on AlteredQualia's skinning example. However, I am looking to hide the model until it is fully loaded. In the provided example, the models are displayed before their texture resources finish loa ...

Adjusting the background color using CSS according to the browser's dimensions

I'm having trouble identifying the issue with this code. The background color remains white and doesn't change as expected. <style type="text/css"> h1 { position: absolute; text-align: center; width: 100%; ...

To ensure that quotes are correctly handled in a string being passed to a JavaScript function within an `onclick`

I am facing an issue with a cycle in a jspx file that I have. The cycle looks like this: <c:forEach var="var" items="${dataFile.list.rows}"> <li> <div> <a href="#" onClick="myFunct('${var.url}','escape(${var ...

Hidden text within a webpage that remains concealed until a specific link is activated

Just getting started with HTML and wanting to add animation to my project. I have a vision of an animation where clicking on an image will split open a half page of text and stuff. It should be similar to this example: ...

Directive in AngularJS is a reusable component that allows

Let me explain my situation. I am dynamically adding a block of code using JavaScript and binding it to my AngularJS scope. Everything seems to be working fine, except for one issue. There is a directive on a text box that works properly. However, the $wat ...

Tips for organizing information within a table

I have been developing a tool that allows users to enter a username, and then I display the data fetched from GitHub related to that particular user. Although each cell in the table is sortable, they all seem to sort data based on the first cell. When I cl ...

Combining various FormGroup types into a single object type in Angular 5

I am currently utilizing the mat-stepper feature from the Angular Material design library. Within my application, I am using 3 separate FormGroups to gather information and send it to a database using the httpClient method. To achieve this, I have defined ...

Javascript splice method mistakenly eliminating the incorrect elements

I have an array of objects like the one below: [{"name":"Rain"},{"name":"Storm"},{"name":"Forest"}] These objects are indexed as follows: [0, 1, 2]. I'm attempting to delete an item at a specific position using this code: $scope.selectedSound ...

Adjusting the color of a box in Threejs through dat.gui.min.js controls

I want to enhance the user experience by allowing them to choose a color from the HEX menu and update the color of the box in the scene using UI controls. Below is the JavaScript code I have implemented for this purpose: // author: Arielle Mueller // date ...

Switch from monochrome to color when hovering inside a clipping mask

I have successfully mastered the technique of changing an image from grey to color on hover using CSS and JavaScript. However, I am curious about whether it is possible to achieve the same effect using a clipping mask. Attached is an image that illustrate ...

Tips on widening a paper to its fullest width while also keeping it versatile and adaptable

How can we ensure that in a React application using Material-UI, the width of a paper always expands to a maximum of 600px, regardless of the width of its contents? We also want to keep the paper flexible, so that when the parent container's width shr ...

Arranging my HTML text fields for optimal organization

I am struggling to format my text fields the way I envision. Here's what I want: - Username field at the top - First and last name underneath each other - Password and confirm password next to each other below names As a newcomer to HTML, I'm fi ...

Steps for creating a horizontal card design

Looking to achieve a card style similar to this: http://prntscr.com/p6svjf How can I create this design to ensure it remains responsive? <div class="recent-work"> <img src="work/mercedes.png"> <h3>Modern website concept</h3&g ...

What is the best approach to tackle this design?

As a newcomer to React, I'm facing challenges in positioning components. The layout I envision is consistent across all pages, with certain elements remaining the same. Should I utilize a grid system for this design? How should I approach achieving th ...