$(this).text() vs $(this).attr("innerText") in Chrome [duplicate] - javascript

This question already has answers here:
'innerText' works in IE, but not in Firefox
(15 answers)
Closed 8 years ago.
I'm a nub in jQuery and javascript in general, so this must be a beginners question.
This line works for me, foo is not empty:
var foo = $("#hello").find("option").filter (function(){return $(this).text() == "BAR";});
This one in the same spot doesn't (foo undefined):
var foo = $("#hello").find("option").filter (function(){return $(this).attr("innerText") == "BAR";});
The only difference is using .text() vs .attr("innerText"). Why the latter doesn't work for me?

.attr() finds HTML attributes attached to the DOM element, it's not looking for the DOM element's JavaScript attributes like innerHTML or innerText. To find such attributes, you need to access the DOM element inside the jQuery object that the selector returns, or in this case, the this reference itself, such as:
var foo = $('#hello').find("option").filter (function(){return this.innerText == “BAR";});
As pointed out by others, this is not advised since it can lead to unexpected behavior and it's also not cross-browser compatible. Just use .text() instead.

.attr() is looking for the attribute innerText on the node. It will give you undefined except if you node look like that :
<div innerText="test"></div>
Maybe your are mixing yourself with .prop('innerText') which get the property innerText of the node. That is the same as .text() except that .text() is safer since jQuery counter compatibility issues..
If you are interested by how jQuery get the text no matter which browser you are, here the relevant code

Related

Is it appropriate to handle an element by its ID (as a var) without getElementById? [duplicate]

This question already has answers here:
Do DOM tree elements with IDs become global properties?
(5 answers)
Why don't we just use element IDs as identifiers in JavaScript?
(5 answers)
Closed 2 years ago.
I've been coding with vanilla JS for quite a few years, but whenever I needed to handle an HTML element with an id attribute I'd reasonably resort to:
var myId = document.getElementById('myId');
When, by mere accident, I actually found out that this works:
function add() {
let span = document.createElement('span');
span.innerHTML = '<br />o hi';
// === THIS: ===
correctId.appendChild(span);
}
<div id="someId"></div>
<input type="button" value="MOAR" onclick="add()" />
<div id="correctId"><strong>Append here: </strong></div>
<div class="someClass"></div>
I was beyond shocked to learn this.
The million dollar question is... Is that even good practice or standard at all? Can I safely use that in my code or is it a very recent addition, deprecated, browser-specific or even dangerous?
I didn't even know how to look for references on this behavior. I tried looking for "element id as variable", "using ids as var names" and so on. Nothing. Everywhere I go people mention document.getElementById(), document.querySelector('#'), jQuery, but never that one behavior - that elements with an id attribute are already available as variables in JavaScript, or at least that's how I understood it.
I'm using Chrome 81.0.4044.138. Can anyone please shed any lights on this?
I don't see any problem with this. All you are doing is getting the reference in an indirect way and then adding it using inner Html. I am no expert but do this all the time.

Turn '$(this)' jquery to javascript 'this' [duplicate]

This question already has answers here:
jQuery object and DOM element
(6 answers)
Closed 7 years ago.
Is it possible to reverse jquery '$(this)' into javascript 'this'?
How can this be done?
jQuery is set based, and lets you access the elements of that set using either indexer notation ([]) or the get method.
So if you have a jQuery set:
var set = $(this);
...you can access its elements via set[0] through set[set.length - 1] and via set.get(0) through set.get(set.length - 1) (get also supports negative indexes for indexing from the end).
In the case of $(this), of course, you don't need to use $() at all — just use this directly. This is true whenever you have a raw DOM reference, whether this or event.target or whatever.
jQuery or $ is primarily just a wrapper function that returns a jQuery object. So removing the $ is all you need to get the normal DOM element this.
this // DOM ELement
$(this) // jQuery object
this // Again just a DOM Element
You need not do anything more. this will always be the primitive DOM Element, it's because you're wrapping it, that it returns you a jQuery object.
jQuery offers .get which does the same too, but offers the convenience of getting a specific element if this is a collection.

How to write a function like `document.getElementsWithAttributeName("attr-name")`? [duplicate]

This question already has an answer here:
Select elements with data attribute *not* using jQuery
(1 answer)
Closed 9 years ago.
Could someone tell me how to write a function: getElementsWithAttributeName("attr-name")?
It should return all elements from the current document that contain the attribute attr-name.
Also, how do I add this function to the document as well?
Any response will be much appreciated.
You can add a method to document just like this:
document.fnName = function(args){ ... };
As Rob W pointed out in the comments, you can just use the existing document.querySelectorAll() method and pass a css selector. If you really wanted this to work like getElementsByAttributeName("attr-name") you could do this:
document.getElementsByAttributeName = function(attrName){
return document.querySelectorAll('[' + attrName+']');
};
Note, this is IE8+ only. (document.querySelectorAll() requires IE9 for CSS3 selectors however.)
references:
MDN: querySelectorAll() docs
CSS-Tricks: The Skinny on CSS Attributes

Javascript $ notation [duplicate]

This question already has answers here:
What is the purpose of the dollar sign in JavaScript?
(12 answers)
Closed 9 years ago.
Please can anyone explain what this javascript code exactly does.
$('#element_id').html(response.title);
I need to access the value of the element_id but I can't using document.getElementById.
Thanks
This code just calls a function named $ and access a method of the returned object.
It's probably jQuery code due to the selector string.
$('#element_id'): Returns a jQuery object for the element with the given ID.
.html(response.title): Sets the inner HTML of the DOM element to response.title.
The raw JavaScript would look like this:
document.getElementById("element_id").innerHTML = response.title;
This code uses probably JQuery. The $ is the basic function defined by JQuery. You can call it to get access to element using a special query language defined by JQuery.
It looks like jQuery, which is a Javascript library. The $('#element_id') creates a jQuery object for the element with the id element_id in the DOM. Then .html(response.title) will put the value of response.title as HTML inside the element.
$ probably refers to jQuery, one of the most frquently used JS libraries.
What this snippet basically does is setting the HTML content of the element with the id element_id to the title attribute of the response object.

How to make $('#some-id') return the same object as getElementById('some-id') [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to get a DOM Element from a JQuery Selector
I have a JavaScript library that takes one of parameters as
element: document.getElementById('file-uploader')
And it works well, though I try to use jQuery instead and error happens then.
element: $('#file-uploader')
I suppose these return different objects so how can I make it with jQuery but return an object of the same kind as if it were returned by getElementById method?
Try -
$('#file-uploader')[0] //or $('#file-uploader').get(0)
This will return the 'naked' JavaScript DOM object, the same as
document.getElementById('file-uploader')
would return. The example above will only return the first element of the matched set, but in a situation where you're searching by id that should be fine.
Try:
$('#file-uploader')[0]
It should be equiv to:
document.getElementById('file-uploader')
you have to use either [0] or .get(0) to return the dom object instead of the jquery:
$('#file-uploader')[0];
or
$('#file-uploader').get(0);

Categories