JAT86
JAT86

Reputation: 1075

How to set a title attribute of a form button (not having an id) using JavaScript

I have a <button> inside a <form>. The button has no id attribute, but the form has, and I want to use JavaScript to add a title attribute to the button.

I tried using querySelector but I cannot get it to work. The code is below:

<form id='largerView' action='#' method='get'>
  <button>Large Version</button>
</form>

JavaScript:

document.querySelector('#largerView>button').title = 'View the larger version of the image';

Upvotes: 0

Views: 575

Answers (1)

Keegan Teetaert
Keegan Teetaert

Reputation: 673

This code adds a title attribute to the first button that appears as a child in the form element.

var form = document.getElementById("largerView");
var button = form.getElementsByTagName("button")[0];
button.setAttribute("title", "TITLE");

Further if you would like to continue using querySelector all you have to do is replace > with a space.

document.querySelector('#largerView button').title = 'View the larger version of the image';

Let me know if you need further help. Cheers.

Upvotes: 1

Related Questions