There was one problem, I want to change the background of one div when I clicked on the button, but when I call it that way -

document.div.style.background = 'url(second_1.jpg) no-repeat'; 

then nothing works, the "Cannot read property 'style' of undefined" is written in the console. Here is the whole code:

Js

 function new_art() { document.div.style.background = 'url(second_1.jpg)'; } 

CSS

 div { background: url(first_1.jpg) no-repeat; width: 15%; height: 87%; } div:hover { background: url(first_2.jpg); } 

HTML

 <div></div> <input type="button" value="Tap me!" onclick="new_art()"> 
  • 2
    document.getElementsByTagName ('div') [0] .style.background = 'url (second_1.jpg)'; - HamSter
  • @ElenaSemenchenko thank you very much, it works! - Mark_8
  • @ElenaSemenchenko please tell me, and how to change the hover in this case? - Mark_8
  • And what about hover? It works for you. - HamSter
  • @ElenaSemenchenko needed a hover to be different too after pressing a button, but I already found the answer to my question) - Mark_8

2 answers 2

This literal error means:

"Dude, I can't read the style property of a non-existent object" !!

In this reconciliation, the face does not correctly address the Dom.
In js, there are several ways to access Dom. Most of them assume that the element has a unique identifier ( id ) or css class.
Here are some of them:
If the element is the first child, the body can be accessed like this: document.body.children[0] .

document.getElementById('id'); // search by id
elem.getElementsByTagName(tag); // searches for all elements with the given tag tag inside the elem element and returns them as a list.
Calling elem.getElementsByClassName(className) returns a collection of elements with class className. Finds an element even if it has several classes, and the desired one is one of them.
The call elem.querySelectorAll(css) returns all the elements inside the elem that satisfy the CSS CSS selector.
The call elem.querySelector(css ) returns not all, but only the first element corresponding to the CSS selector css.
Here you can read more

    The problem is the string:

     document.body.div.style.background = 'url(second_1.jpg) no-repeat'; 

    because it is not possible to access the div element via document.body .

    And what if you have 2 div elements in the body, how do you know which one to call?

    Therefore, if you want to find the item you need, then use:

     document.getElementById('id элемента').style.background = 'url(second_1.jpg) no-repeat';