EverydayDeveloper
EverydayDeveloper

Reputation: 1150

HTML DOM getElementsByTagName issue

Currently, both this is using a button, but is there a possible to have this query without a button but just onclick?

Changes the target of the anchor to google.com:

<button onclick="document.querySelectorAll('ul>li>a').forEach(function(link){link.href='http://google.de';});"> ChangeHREF </button>

Changes the color of the header of the page:

<button onclick='(document.getElementsByTagName("h1")[0]).style.color="blue"'>XSS attach</button>

Upvotes: 0

Views: 125

Answers (2)

Sascha A.
Sascha A.

Reputation: 4616

Add an eventlister for click on a tag e.g. a DIV that starts a function (change). In this function get with querySelector your header H1 and a class blue. Via CSS the color of the header changes to blue.
So you don't need a button for this.

document.getElementById('myDiv').addEventListener('click', change);

function change() {
    document.querySelector('h1').classList.add("blue");
}
h1.blue {
  background: blue;
}
<h1>Header</h1>
<div id="myDiv">Press this DIV for change H1 to blue</div>

Upvotes: 2

Umutambyi Gad
Umutambyi Gad

Reputation: 4101

of course you can here is one I used div and you can use other but in the way makes sense like you can't use select

change.onclick = () => {
  document.getElementsByTagName('h1')[0].style.color = 'red';
}
<h1>Hello world</h1>
<div id="change">Change Color</div>

change.onclick = () => {
  document.querySelectorAll('a').forEach(link => {
    link.href = 'http://google.de';

  });
  var links = document.getElementsByTagName('a');
  console.log(links[0].href);
  console.log(links[1].href);
}
<a href="">a</a>
<a href="">b</a>
<div id="change">Change</div>

Upvotes: 1

Related Questions