Reputation: 21
So I have this HTML code and I want to call the button with java script. It is for a 404 error page test I am making. The code is located in the body of the html and everything displays fine.
<div class="contain" id="container">
<div class="content" id="cont">
<h2>404</h2>
<h4>Opps! Page not found</h4>
<p>The page you were looking for doesn't exist. You may have mistyped the adress or the page may have moved</p>
<a href="#">Back To Home</a>
</div>
</div>
However I do not know how to set a var (or let or const) to the button. I get errors when I try to get the id then get the class name then the button. I have even tried something like this.
const buttons = document.getElementById("container").getElementById("cont").querySelector('a');
and it gives me an error because it sets the document.getElementById("container") = null; I am new to HTML and Javascript so anything helps! Thank you
Upvotes: 2
Views: 1293
Reputation: 13082
You can use your debugger. In the «inspector» tab, right click the target element, and choose «copy» «css selector».
This gives in this case: #cont > a:nth-child(4)
See screenshot: https://i.sstatic.net/ICdgO.png
Then you can use querySelector, like this:
document.querySelector("#cont > a:nth-child(4)").textContent = "Modified by js!"
<div class="contain" id="container">
<div class="content" id="cont">
<h2>404</h2>
<h4>Opps! Page not found</h4>
<p>The page you were looking for doesn't exist. You may have mistyped the adress or the page may have moved</p>
<a href="#">Back To Home</a>
</div>
</div>
Upvotes: 1
Reputation: 478
can you use querySelector method :
var data = document.querySelector("#container #cont a");
console.log(data.href);
<div class="contain" id="container">
<div class="content" id="cont">
<h2>404</h2>
<h4>Opps! Page not found</h4>
<p>The page you were looking for doesn't exist. You may have mistyped the adress or the page may have moved</p>
<a href="#">Back To Home</a>
</div>
</div>
Upvotes: 1