Accessing a specific child div within a parent div using JavaScript and CSS

Struggling to target and modify the style of the child div within id="videoContainer"

<div id="videoContainer">
  <div style="width: 640px; height: 360px">   <------- this is the target
    <video
      src=""
      preload="auto"
      autoplay=""
      style="width: 100%; height: 100%"
    ></video>
  </div>
</div>


const videoContainer = document.getElementById('videoContainer')
document.getElementById('videoContainer').children?.[0]?.setAttribute("style", `width: 150px; height: 200px;`);

Answer №1

To target specific child elements, you can utilize querySelector along with the direct child operator `>` (and possibly `:first-child` if there are multiple child divs) as shown in the example below:

const videoContainer = document.querySelector('#videoContainer > div')
videoContainer.style.width =  "150px"
videoContainer.style.height = "200px"
console.log("videoContainer width is", videoContainer.style.width)
/* additional styles that may be necessary */
#videoContainer video {
  object-fit: contain;
}
<div id="videoContainer">
  <div style="width: 640px; height: 360px">   <!------- select this element -->
   <video src="//samplelib.com/lib/preview/mp4/sample-5s.mp4"       
    preload="auto"
    autoplay=""
    style="width: 100%; height: 100%"></video>
  </div>
</div>

The use of `object-fit: contain` will ensure your video scales appropriately within its parent container. You might also consider using `cover` or other options based on your requirements. For more insights, refer to this discussion on simulating `background-size:cover` for `video` and `img` elements.

Answer №2

To customize the target, you can assign an id or class and reference it in the CSS using #Idname or .Classname like so:

file.html:

<div id="videoContainer">
  <div id="idname" class="classname" style="width: 640px; height: 360px">   
    //....
  </div>
</div>

file.css:

#idname {
    width: 640px;
    height: 360px;
}
//OR
.classname {
    width: 640px;
    height: 360px;
}

You can also achieve this with CSS by targeting specific elements within the video container:

#videoContainer > div {
    width: 640px;
    height: 360px;
}

Another option is to use JavaScript to dynamically adjust the styling:

const videoContainer = document.getElementById("videoContainer").firstChild; 
// or
const videoContainer = document.getElementById("videoContainer").childNodes[0]; 
//or
const videoContainer = document.querySelector('#videoContainer > div');

videoContainer.style.width = '640px';
videoContainer.style.height = '360px';

Answer №3

Here's a simple solution for you. I hope this helps to answer your question.

document.getElementById("videoContainer").children[0].style.background="red";
<div id="videoContainer">
  <div style="width: 640px; height: 360px">  
    <h1>Your Content </h1>
  </div>
</div>

Answer №4

This method can be employed like this:

document.getElementById("specific_element_id").style.property = new style

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 graphic is displayed at a width of 50%

I am currently working on a FrontEnd project and implementing Bootstrap 3 for the grid system. Additionally, I am utilizing art direction with the picture element. However, I seem to be facing an issue with the images. Every time I include the following s ...

Creating artwork: How to resize images without losing clarity

Struggling to display an image in a canvas element that needs to be a certain percentage of its parent container's width. Despite my efforts, the image seems to blur once added to the canvas, which is not the desired effect. I attempted to disable th ...

Ways to deactivate the submit button using Cookies, sessions, or local storage

Although cookies and storage can be deleted, they can still help prevent many human spammers who are unaware of this. How can I temporarily disable the form submit button on a specific page for just one day? I want to create a code that saves "Submitted" ...

Having trouble transferring ASP server control value to a Javascript function

Currently working with ASP.NET 2.0. My Entry Form contains various ASP.NET Server Controls, such as TextBoxes. I want to pass the value of a TextBox on the onBlur event. Here is an example of a TextBox code: <asp:TextBox ID="txtTotalTw" Width="80px" r ...

Writing a function to determine if an HTML element is present

Is there a way to create a function that checks for the existence of an element with a specific id? I have a list of IDs stored in an array: let CartArray = ["cart-0", "cart-1", "cart-2", "cart-3"]; This is the Java ...

Utilizing Angular partials within specific views with the assistance of ui-router

I am currently working on developing a MEAN application and facing some challenges while handling ui-router. Within my index.html file, I have set up the template for the entire website including a header, sidebar, and content area where I have placed < ...

What is the procedure for attaching console.log to "l" in vue.js?

The code in main.js includes the following: window.l = function () { } try { window.l = console.log.bind(console) } catch (e) { } It functions properly in non-Vue applications. However, when trying to use it in a Vue action/method like this: l("test") ...

The props in Vue 3 are not functioning as expected in child components even after being bound correctly, resulting in undefined values in the child component

Exploring the realms of Vue and Laravel, I find myself in new territory. As the parent element, I fetch items from the database successfully. Now, the task at hand is to pass this data to the child component. <template> <div class="todoList ...

The React Js error message shows an 'Uncaught (in promise)' TypeError that prevents reading an undefined property

Struggling with passing the response from an Ajax request to another function in React. Although I am able to receive the response, I cannot pass it to { this.showBattersData(data); } where I need to render the DOM. It's clear that something is missin ...

Mongoose and ES6 promises are not delivering the expected results

I'm currently working on a piece of code that involves creating an array of promises to save specific numbers. The issue I'm facing is that when the output is printed, it displays the same record 10 times. Below is the code snippet: 'use s ...

Position the float input to the right on the same line as an element

This Angular code contains a challenge where I aim to have text at the start of a column and an input box on the right side of the page, both aligned on the same line. The issue lies in the code which floats the input to the right but disrupts the alignme ...

In Javascript, navigate to a specific section by scrolling down

Currently, I am in the process of enhancing my portfolio website. My goal is to incorporate a CSS class once the user scrolls to a specific section on the page. (I plan to achieve this using a JavaScript event). One approach I am considering is initially ...

JavaScript's GET method fails to retrieve the complete JSON file

I am facing an issue with a substantial JSON file that my JavaScript code is unable to pull in entirely. When I check the Network tab in Firefox developer tools, it shows that the data stops at around line 57,301 out of 528,342 lines in the JSON file. Ini ...

Wrap it in a ReactJS container tag

Today I encountered a frustrating issue while diving into ReactJS. I'm excited to learn by getting my hands dirty, but unfortunately, I keep running into this error: Adjacent JSX elements must be wrapped in an enclosing tag (47:14) And here's t ...

The Bootstrap modal causes the scrollbar to vanish upon closure

Despite trying numerous solutions and hacks on this issue from StackOverflow, none of them seem to work for me. Currently, I am utilizing a modal for the login process in Meteor (e.g. using Facebook login service) which triggers a callback upon successful ...

Tips for stopping automatic scrolling (universal solution)

Issue or Inquiry I am seeking a way to disable actual scrolling on an element while still utilizing a scrollbar for convenience (avoiding the need for manual JavaScript implementations instead of relying on browser functions). If anyone has an improved s ...

What might be causing the issue in the build process of my next.js project?

**Why is my Node.js YAML file causing an error?** name: Node.js CI on: push: branches: [ "main" ] pull_request: branches: [ "main" ] jobs: build: runs-on: ubuntu-latest strategy: matrix: node-ver ...

Customizing external elements with React's inline styling feature

Trying to use React to style elements generated by a third-party library has been a challenge. In the snippet below, I was able to achieve the desired styling using CSS, but now I am looking to accomplish the same using JavaScript. This way, users can defi ...

JavaScript code for displaying and concealing elements

I have a simple requirement where I need to check for a variable and display or hide a class based on its value. This is being done on a SharePoint publishing page. The snippet below is not working as expected: if (source === 'show') { $(&a ...

React JS functionality does not support Bootstrap tooltips

I'm attempting to implement a tooltip in my React app, but I'm experiencing issues with it not displaying properly. I am utilizing vanilla Bootstrap for this purpose. I've included the following script tag in my index.html file to import the ...