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

Unable to utilize SASS variables in Angular from a global file, even though other styles are functioning correctly

After implementing the SASS code in my component's style, it functions correctly. $test-color: pink; div{ background-color: $test-color; } However, when I transfer the definition to styles.scss, the desired outcome is not achieved. I have attempted u ...

Converting dynamic content within a div into an interactive link

I am currently working with Longtail's JW Player and facing some difficulties with a basic function. Since I am not familiar with the programming language terminologies, I will describe the issue step by step: There is a JavaScript code that displays ...

Custom pagination for next/previous links in Django REST framework

When it comes to backend operations, I have integrated the PageNumberPagination as the DEFAULT_PAGINATION_CLASS. Since I am utilizing vue.js along with fetch, there is no need for me to include the entire URL structure provided by django-rest-framework: " ...

PHP - contact form is live for just 2 hours daily

Hello, this is my first time here and I could really use some assistance. Please bear with me as English is not my strong suit compared to most people here, but I'll do my best to explain my query. So, I have a PHP script for a contact form on my web ...

What is the reason behind localStorage.getItem consistently returning a string value?

Something strange is happening. In the lib.dom.d.ts file, the type for localstorage.getItem shows as 'string | null', but in my app it always returns a string. Why is this discrepancy occurring? ...

tips for accessing a PHP variable within an AJAX success function and setting it as a JavaScript variable

How can I access a PHP back end variable in a front-end AJAX success callback function? Here is my PHP code: if($_POST["action"] == 'check_ot_count') { $totaltime = 0; $ot_hours = $_POST["test"]; $month = $_P ...

AngularJS directive for jQuery Handsontable is a powerful tool for creating interactive

I've been experimenting with using jQuery handsontable in conjunction with an angular directive, but I've encountered a strange issue. Whenever I type something into the cells, the characters appear outside of the table instead of inside it. Oddl ...

Incorporate a website design template into your Visual Studio project

I have a website application that I created but it's currently empty. I would like to add some style to it using online free website templates that I downloaded. However, I'm unsure of how to incorporate the css, font, and images folders into the ...

Tips on using htmlspecialchars in combination with a href:To safely include links in

If I have the following code: $text = "please visit this <a href='http://example.com'>site</a>." $text = htmlspecialchars($text); echo $text; The output will be please visit this <a href='http://example.com'>site< ...

Is there a way to apply multiple colors to a h1 tag in HTML?

I need help with adding multicolor to a heading on my website using CSS. I am trying to define colors using the span element with different classes for each text section. However, the colors are not showing up as expected and there seems to be spacing issu ...

Parsing HTML with Qt library isn't able to detect any elements

I am currently working on a web crawling application. Within the code, I have the following snippet: // Normally, the HTML content is retrieved from the web using QNetworkAccessManager & QNetworkReply: // QString htmlCode = this->reply->readAll( ...

Display the GIF when the mouse hovers over it, but ensure it plays just a single time

Is it possible to make a GIF only play once when you hover over it on a website? I want to avoid the animation repeating if the user hovers over it again without refreshing the page. Currently, I have a static image that changes to a gif on mouseover, but ...

CSS - Layering <divs> on top of clear <div>'s

Is there a method to eliminate the transparency of content/images within a <div> that is transparent? Below is the provided HTML: <div id="main-button-wrapper" class="left"> <div id="button-bg-layer" class="box-bg-layer corner ...

What is the best way to create a function that shifts a musical note up or down by one semitone?

Currently developing a guitar tuning tool and facing some hurdles. Striving to create a function that can take a musical note, an octave, and a direction (up or down), then produce a transposed note by a half step based on the traditional piano layout (i. ...

The for loop unexpectedly interrupts a different array

Hey there, I've been working with puppeteer and came across an issue with the following code snippet: console.log(dealsId[i]); for (var i = 0; i < sizes.length; i++) { var refIdClasses = await sizes[i].$eval('input', a => a.getAtt ...

Combining two objects by aligning their keys in JavaScript

I have two simple objects that look like this. var obj1 = { "data": { "Category": "OUTFLOWS", "Opening": 3213.11, "Mar16": 3213.12, "Apr16": 3148.13, "May16": 3148.14, "Jun16" ...

The hover effect flickers in Firefox, but remains stable in Google Chrome

Here is an example link to check out: I am facing a dilemma on how to solve this issue and unsure if it is related to jQuery or the DOM structure. If you have any suggestions, they would be greatly appreciated. Thank you! ...

Tips for implementing validation on dynamically inserted fields in a form

My form has two fields, and the submit button is disabled until those fields are filled with some text. However, if I add a third field dynamically using AngularJS, validation will not be supported for the new field. Check out the example here <butto ...

Turn off info windows for businesses and other points of interest, except for those within your own polygons on Google Maps

Is there a way to make only the infowindows attached to my polygons clickable on Google Maps? I don't want Points of Interests like Restaurants to have clickable infowindows. I tried changing the map style to hide business labels, but infowindows stil ...

Changing the opacity on hover doesn't seem to be working

I currently have a simple dropdown menu where the different menu choices are supposed to change opacity when hovered over. The default opacity is set at 0.5. Below is the hover function in my jQuery code: $('#cat1 > li > a').hover(functio ...