Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
brandonlind2
7,823 PointsCan someone explain this js syntax?
I was watching a course video and the teacher used this syntax, can someone explain this?
//I don't understand this single [ , also I don't understand how you can pass type=text.
listItem.querySelector("input[type=text");
//I thought you had to change attribute properties like this?
var input= listItem.querySelector("input");
input.type=text;
1 Answer
Chris Shaw
26,676 PointsHi Brandon,
The first line you have above is an example of using an attribute selector which is part of the ES5 spec and allows you to select elements by specific attributes, this syntax is inline with the CSS 2.1 and CSS3 spec's. As an example, the below JavaScript and CSS will make the same query against your DOM with the exception that querySelector only works on a single instance of the defined element whereas the CSS will target all instances.
/* Targets all instances of the element */
input[type=text] {
/* Do some cool stuff */
}
// Only targets the first instance of the element
var input = document.querySelector('input[type=text]');
If you want your JavaScript to also target all instances, you can use querySelectorAll instead.
You can find more information about attribute selectors on MDN using the below link. https://developer.mozilla.org/en/docs/Web/CSS/Attribute_selectors
Hope that helps.
brandonlind2
7,823 Pointsbrandonlind2
7,823 PointsThanks
brandonlind2
7,823 Pointsbrandonlind2
7,823 Pointsis this listItem.querySelector("input[type=text") a type then, since there isn't a closing bracket? This is how the instructor used it and the code seemed to work fine, did it just happen to work fine?