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

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

Related

Use custom tag using JavaScript only [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 6 years ago.
On my site, as a little footer I guess, I use the tag <joexn id="yo">
and the javascript
var div = document.getElementById('yo');
div.insertAdjacentHTML( 'beforeBegin', 'joexn.com' );
This produces a watermark/footer and want I want to know is how can I change it so the tag is just <joexn> using Javascript only. I want minimalist code only and no clutter. I tried using document.getElementByTagName('joexn'); but that didn't work.
What's the easiest method?
I don't know why this has been marked as duplicate, it is nothing like that other question.
try using document.querySelector(): DEMO
var div = document.querySelector('joexn');
div.insertAdjacentHTML( 'beforeBegin', 'joexn.com' );
document.getElementsByTagName('joexn') should work. Mind you, you have a typo in the usage of this method. It is getElements and not getElement.
This method returns an HTMLCollection object which is an array-like object. So, to get the element itself, you can do
var joexnElement = document.getElementsByTagName('joexn')[0];
And, then do the rest...

Getting div by class name and returning it in javascript [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 7 years ago.
I am trying to inject some javascript into a web page using a very simple js script:
var c = document.getElementsByClassName("main").innerHTML;
alert(c);
I want to set an alert of the text (and only the text) in the div with class="main". Currently the script is making an alert pop up saying 'undefined'. What am I doing wrong, the class name is definitely correct, and I have searched stackoverflow and other sources, having experimented with .innerHTML and .textContent but nothing seems to be able to simply return a var of text.
getElementsByClassName returns an array like object. There is no innerHTML property on it. You need to either act on all the divs returned or a specific one. See docs for further examples. https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
document.getElementsByClassName returns an array because there could be multiple classes with the same class name.
Try doing
var c = document.getElementsByClassName("main")[0].innerHTML;
alert(c);
The issue is that you are returning a set of nodes (HTMLCollection). All elements with the class "main" (getElementsByClassName). For example, this will show you the first element's innerHTML
var c = document.getElementsByClassName("main")[0].innerHTML;
alert(c);
However, a more standardized approach for this would be to use querySelector like this
var c = document.querySelector(".main").innerHTML;
alert(c);
With getElementsByClassName() it returns an array(in this case a group of elements) which you have to define an offset to mark which one of the elements you want to use:
document.getElementsByClassName("main")[0].innerHTML;//0 returns the first element
JSFiddle Demo
If you want to select all the elements of the class, the easiest way is to use a loop:
var element =document.getElementsByClassName("main");
for($i=0;$i<=element.length;$i++){
alert(element[$i].innerHTML);
}
JSFiddle Demo

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

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

Jquery Element Usage [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get a DOM Element from a JQuery Selector
I know using normal javascript i can do
formitem.validity.valid
or
formitem.checkValidity();
How do i use Jquery to call these functions?
Below im using a custom attribute selector to get my element but cant seem to use it like below...
$('[data-dependID=pobText]').validity.valid
or
$('[data-dependID=pobText]').formitem.checkValidity();
Simple but how do i do this?
You need to get DOM Node for that:
$('[data-dependID=pobText]').get(0).validity.valid;
$('[data-dependID=pobText]').get(0).formitem.checkValidity();
Use Get,
i.e.
$('[data-dependID=pobText]').get(0).formitem.checkValidity();
Use .get(n) to get the nth element as a DOM object, or just [n]
$('selector').get(n).foo
or
$('selector')[n].foo
jQuery calls to the DOM return an array-like object and so you can access the DOM elements in the "array" by an index. The get() method does the same thing, only that it encapsulates this in a function call (which is an overhead).
Better use the index instead:
$('[data-dependID=pobText]')[n].validity.valid;
$('[data-dependID=pobText]')[n].checkValidity();

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