skip to Main Content

I can’t access the child (div) to change the background image. I want to change it by it’s parent. How?

<section class="l-section wpb_row frenach-header">
<div class="l-section-img" role="img" data-img-width="1587" data-img-height="700" style="background-image: url(https://example.com/wp-content/uploads/2024/03/french-header.webp);"></div>
</section>

How can I access div tag through its parent (section) to change the background image?

3

Answers


  1. You would need to create a certain CSS snippet to create a hierarchy of parent to child properly.

    See this example for reference:

    .l-section .l-section-img {
      background-image: url("https://picsum.photos/1587/1587");
      width: 1587px;
      height: 700px;
    }
    <section class="l-section wpb_row frenach-header">
      <div class="l-section-img" role="img" data-img-width="1587" data-img-height="700"></div>
    </section>

    Here, the format of hierarchy is — .[parent class] [child class]

    Login or Signup to reply.
  2. I am not sure if I understood your question correctly.

    Solution #1:


    How can I access div tag through its parent (section) to change the background image?

    Have you tried variables? something like that:

    .parent {
      --image-from-parent: url("some-url");
      ...
    }
    
    .child {
      background-image: var(--image-from-parent);
      ...
    }
    

    Solution #2:


    You can use selectors:

    .parent > div {
      background-image: url("some-url");
    }
    
    Login or Signup to reply.
  3. You can use querySelector. The following query search for a div inside section that has a attribute named ‘role’, which is set to ‘img’ and returns the first one. Then you can access the background image URL though .style.

    const el = document.querySelector('section div[role="img"]').style.backgroundImage;                                           
    console.log(el);
    <section class="l-section wpb_row frenach-header">
    <div class="l-section-img" role="img" data-img-width="1587" data-img-height="700" style="background-image: url(https://example.com/wp-content/uploads/2024/03/french-header.webp);"></div>
    </section>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search