Difference between attr=val, attr="val" and attr='val' in Javascript?

Asked

Viewed 139 times

5

There is some difference in using the selector in the following ways, or one that is "correct"?

[name="val"] [name='val'] [name=val]

3 answers

4


From the selector’s point of view, there is no difference, but there are some considerations:

  • Single or double quotes depend on how the command started not to conflict. Example:

$('input[name="val"]') or $("input[name='val']")

  • If the name contains special characters such as [] for example, the selector will always need quotes, for example:

$("input[name='Campo[0].val']")

  • In other cases, with a simple name you can use without quotation marks:

$('input[name=val]')

console.log($('input[name=val]').val());
console.log($('input[name="val"]').val());
console.log($("input[name='val']").val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' name='val' value='teste' />

  • If I use [name=name] may at some point be a problem?

  • No, he will always look for an element where the property name is "name". Now, if your code js take the name dynamically, and you don’t know how it will come (it can come with characters like $[], use quotes so there are no surprises.

3

A good practice is to delimit the value of the selected attribute by double quotes ("valor") or single quotes ('valor'), depending on which quotes were used in the selector.

Examples:

$("input[name='val']") // aspas duplas no seletor
$('input[name="val"]') // aspas simples no seletor

Although the unquoted form can work in many cases, you can omit the quotation marks if the attribute value has only alphanumeric characters (including the hyphen (-) and the underscore (_).

Examples:

<input name="val@" value="Enviar">
-> $("input[name=val@]").val()   // Retorno: erro! "@" não é alfanumérico
-> $("input[name='val@']").val() // Retorno: "Enviar"

<input name="val1 val2" value="Enviar">
-> $("input[name=val1 val2]").val()   // Retorno: erro! "espaço" não é alfanumérico
-> $("input[name='val1 val2']").val() // Retorno: "Enviar"

Functional examples:

The question of the hyphen and the underscore. As stated, both characters are part of the group alphanumeric, so there is no error if used in attribute selector without quotes:

Ex. 1 with quotation marks:

console.log($("input[name='-']").val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="-" value="Enviar">

Ex. 2 without quotation marks:

console.log($("input[name=-]").val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="-" value="Enviar">

Edit

Also raised in the comments about using the selector in pure Javascript, that there are exceptions in the use of the hyphen in the attribute name without the use of quotation marks.

document.querySelector("input[name=-]") // ERRO!
document.querySelector("input[name=--]") // OK!
document.querySelector("input[name=-1]") // ERRO!
document.querySelector("input[name=--1]") // OK!
document.querySelector("input[name=-a]") // OK!
  • It is not true, it is not a question of alphanumeric, what will cause is a mistake like input[name=val@]' is not a valid selector, so much it could do this input[name=_-] and will return one or more inputs that are like this <input name="_-">, note that [name=-] fails by accusing the same error I quoted, but [name=_-] works normally. It’s not a question of alphanumeric, it’s a matter of syntax even and how it works, the point is that many signs can confuse the syntax, so the interpreter will not miss anything, and so there are delimiters (such as quotation marks)

  • @Guilhermenascimento Obg for the information. I will analyze here.

  • @Guilhermenascimento I added in the answer two examples that contradict what you said.

  • Don’t test with jQuery, do with Javascript (document.querySelector), the question is about selectors and Javascript, frameworks can simply change the behavior for some reason to facilitate or simply the authors have not thought to pass on the problem, after all jQuery is not 100% querySelector, it uses it, but internally, Which means there are more routines. --- See, this is the result I’ve been running via console inside your own Stacksnippet, without changing the HTML, just by running a command: https://i.stack.Imgur.com/eaBfJ.png

2

My answer is only to complement the others.

If you are using the selectors of Jquery it would be interesting to follow the suggested patterns of the framework:

Quotation marks

jQuery uses double quotes.

var double = "I am wrapped in double quotes";

Strings that need quotation marks internally should use quotation marks double outside and single quotes inside:

var html = "<div id='my-id'></div>";

Source: jquery.org

  • 2

    Nice, cool, this Urahara avatar :)

  • I don’t agree, one that jQuery is just a framework, another thing that this has nothing to do with jQuery, selectors exist independently of jQuery, the idea of using simple quotes in yes is useful and I agree, the same could be done in reverse '<div id="foo">', which could even be better, and at ES6 could even use the grave accent. I’m not disagreeing with the answer, I’m disagreeing with how it was posed.

  • I get your point, maybe I misexpressed it. I know that jquery is just a framework and the existence of selectors idependente of it, but from what I saw of the question he was using jQuery selectors and my intention was just to say that if you are going to use a framework it would be interesting to follow his patterns, although he might be using a querySelector. I’ll try to change the answer I think it sounded arbitrary instead of suggestive.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.