Getting elements using Javascript - javascript

I have a bunch of input elements that have a particular substring in their IDs. Using javascript, is there a way to get these elements as an array? I wouldn't know the full ID - only the substring.
Is this any simpler if I use JQuery?

How about a non-jQuery answer...hmmm!?
function getAndFilter(elems, filter) {
var length = elems.length,
ret = [];
while (length--) {
if(filter(elems[length])) {
ret[ret.length] = elems[length];
}
}
return ret;
}
getAndFilter(document.getElementsByTagName('input'), function(input) {
// Your custom logic/rule goes here:
return input.id.substr(0,5) === 'HELLO';
});

Quite easy with jQuery. Example:
$("li[id^='comment']")
Select all "li" where id starts with "comment".
EDIT
To get those into an array:
var myArray = new Array;
$("li[id^='comment']").each(function() {
var thisId = $(this).attr("id");
myArray.push(thisId);
});

its simpler if you use jquery, otherwise you will have to start from document body, get its children, parse their ids, select matching elements, and continue down the tree.

jquery is definitely a good way to go.
Check out the attribute filters at jquery.com

Selectors API runs.
document.querySelectorAll("input[id*='yoursubstring']")
Works in IE8+, WebKit (Google Chrome, Safari), seems will work in next Opera and FF.

Related

.find is not working

hi this is my problem im currently looping all the selected element using jquery selector and tried to use .find(Selector) of jquery but i think its not working or is it possible to find an element using this code
for (var i = 0; i < $('.MainElement').find('.ItemGroup').length; i++) {
var CurrentSelectedGroup = $('.MainElement').find('.ItemGroup')[i].find('span');
}
I debugged this code and its returning a unavailable but when i tried to jquery select the element manually its working is it possible to do this??
i need to select the span inside the current element inside the loop
I have searched in google i didnt find any
Though eq() as given below works, a better approach will be is to use .each() for iteration, as you are running your selector multiple times in your script
$('.MainElement').find('.ItemGroup').each(function(){
var CurrentSelectedGroup = $(this).find('span');
})
or at the least cache the value of your selector and then reuse it in your loop
use eq()
var CurrentSelectedGroup = $('.MainElement').find('.ItemGroup').eq(i).find('span');
NOTE: $('.MainElement').find('.ItemGroup')[i] will return javascript object not jquery
Try this as it's much cleaner:
$('.MainElement').find('.ItemGroup').each(function() {
var CurrentSelectedGroup = $(this).find('span');
});

Select tags that starts with "x-" in jQuery

How can I select nodes that begin with a "x-" tag name, here is an hierarchy DOM tree example:
<div>
<x-tab>
<div></div>
<div>
<x-map></x-map>
</div>
</x-tab>
</div>
<x-footer></x-footer>
jQuery does not allow me to query $('x-*'), is there any way that I could achieve this?
The below is just working fine. Though I am not sure about performance as I am using regex.
$('body *').filter(function(){
return /^x-/i.test(this.nodeName);
}).each(function(){
console.log(this.nodeName);
});
Working fiddle
PS: In above sample, I am considering body tag as parent element.
UPDATE :
After checking Mohamed Meligy's post, It seems regex is faster than string manipulation in this condition. and It could become more faster (or same) if we use find. Something like this:
$('body').find('*').filter(function(){
return /^x-/i.test(this.nodeName);
}).each(function(){
console.log(this.nodeName);
});
jsperf test
UPDATE 2:
If you want to search in document then you can do the below which is fastest:
$(Array.prototype.slice.call(document.all)).filter(function () {
return /^x-/i.test(this.nodeName);
}).each(function(){
console.log(this.nodeName);
});
jsperf test
There is no native way to do this, it has worst performance, so, just do it yourself.
Example:
var results = $("div").find("*").filter(function(){
return /^x\-/i.test(this.nodeName);
});
Full example:
http://jsfiddle.net/6b8YY/3/
Notes: (Updated, see comments)
If you are wondering why I use this way for checking tag name, see:
JavaScript: case-insensitive search
and see comments as well.
Also, if you are wondering about the find method instead of adding to selector, since selectors are matched from right not from left, it may be better to separate the selector. I could also do this:
$("*", $("div")). Preferably though instead of just div add an ID or something to it so that parent match is quick.
In the comments you'll find a proof that it's not faster. This applies to very simple documents though I believe, where the cost of creating a jQuery object is higher than the cost of searching all DOM elements. In realistic page sizes though this will not be the case.
Update:
I also really like Teifi's answer. You can do it in one place and then reuse it everywhere. For example, let me mix my way with his:
// In some shared libraries location:
$.extend($.expr[':'], {
x : function(e) {
return /^x\-/i.test(this.nodeName);
}
});
// Then you can use it like:
$(function(){
// One way
var results = $("div").find(":x");
// But even nicer, you can mix with other selectors
// Say you want to get <a> tags directly inside x-* tags inside <section>
var anchors = $("section :x > a");
// Another example to show the power, say using a class name with it:
var highlightedResults = $(":x.highlight");
// Note I made the CSS class right most to be matched first for speed
});
It's the same performance hit, but more convenient API.
It might not be efficient, but consider it as a last option if you do not get any answer.
Try adding a custom attribute to these tags. What i mean is when you add a tag for eg. <x-tag>, add a custom attribute with it and assign it the same value as the tag, so the html looks like <x-tag CustAttr="x-tag">.
Now to get tags starting with x-, you can use the following jQuery code:
$("[CustAttr^=x-]")
and you will get all the tags that start with x-
custom jquery selector
jQuery(function($) {
$.extend($.expr[':'], {
X : function(e) {
return /^x-/i.test(e.tagName);
}
});
});
than, use $(":X") or $("*:X") to select your nodes.
Although this does not answer the question directly it could provide a solution, by "defining" the tags in the selector you can get all of that type?
$('x-tab, x-map, x-footer')
Workaround: if you want this thing more than once, it might be a lot more efficient to add a class based on the tag - which you only do once at the beginning, and then you filter for the tag the trivial way.
What I mean is,
function addTagMarks() {
// call when the document is ready, or when you have new tags
var prefix = "tag--"; // choose a prefix that avoids collision
var newbies = $("*").not("[class^='"+prefix+"']"); // skip what's done already
newbies.each(function() {
var tagName = $(this).prop("tagName").toLowerCase();
$(this).addClass(prefix + tagName);
});
}
After this, you can do a $("[class^='tag--x-']") or the same thing with querySelectorAll and it will be reasonably fast.
See if this works!
function getXNodes() {
var regex = /x-/, i = 0, totalnodes = [];
while (i !== document.all.length) {
if (regex.test(document.all[i].nodeName)) {
totalnodes.push(document.all[i]);
}
i++;
}
return totalnodes;
}
Demo Fiddle
var i=0;
for(i=0; i< document.all.length; i++){
if(document.all[i].nodeName.toLowerCase().indexOf('x-') !== -1){
$(document.all[i].nodeName.toLowerCase()).addClass('test');
}
}
Try this
var test = $('[x-]');
if(test)
alert('eureka!');
Basically jQuery selector works like CSS selector.
Read jQuery selector API here.

remove everything that is inside the actual tag [duplicate]

Is it possible to remove all attributes at once using jQuery?
<img src="example.jpg" width="100" height="100">
to
<img>
I tried $('img').removeAttr('*'); with no luck. Anyone?
A simple method that doesn't require JQuery:
while(elem.attributes.length > 0)
elem.removeAttribute(elem.attributes[0].name);
Update: the previous method works in IE8 but not in IE8 compatibility mode and previous versions of IE. So here is a version that does and uses jQuery to remove the attributes as it does a better job of it:
$("img").each(function() {
// first copy the attributes to remove
// if we don't do this it causes problems
// iterating over the array we're removing
// elements from
var attributes = $.map(this.attributes, function(item) {
return item.name;
});
// now use jQuery to remove the attributes
var img = $(this);
$.each(attributes, function(i, item) {
img.removeAttr(item);
});
});
Of course you could make a plug-in out of it:
jQuery.fn.removeAttributes = function() {
return this.each(function() {
var attributes = $.map(this.attributes, function(item) {
return item.name;
});
var img = $(this);
$.each(attributes, function(i, item) {
img.removeAttr(item);
});
});
}
and then do:
$("img").removeAttributes();
One-liner, no jQuery needed:
[...elem.attributes].forEach(attr => elem.removeAttribute(attr.name));
Instead of creating a new jQuery.fn.removeAttributes (demonstrated in the accepted answer) you can extend jQuery's existing .removeAttr() method making it accept zero parameters to remove all attributes from each element in a set:
var removeAttr = jQuery.fn.removeAttr;
jQuery.fn.removeAttr = function() {
if (!arguments.length) {
this.each(function() {
// Looping attributes array in reverse direction
// to avoid skipping items due to the changing length
// when removing them on every iteration.
for (var i = this.attributes.length -1; i >= 0 ; i--) {
jQuery(this).removeAttr(this.attributes[i].name);
}
});
return this;
}
return removeAttr.apply(this, arguments);
};
Now you can call .removeAttr() without parameters to remove all attributes from the element:
$('img').removeAttr();
One very good reason to do this for specific tags is to clean up legacy content and also enforce standards.
Let's say, for example, you wanted to remove legacy attributes, or limit damage caused by FONT tag attributes by stripping them.
I've tried several methods to achieve this and none, including the example above, work as desired.
Example 1: Replace all FONT tags with the contained textual content.
This would be the perfect solution but as of v1.6.2 has ceased to function. :(
$('#content font').each(function(i) {
$(this).replaceWith($(this).text());
});
Example 2: Strip all attributes from a named tag - e.g. FONT.
Again, this fails to function but am sure it used to work once upon a previous jQuery version.
$("font").each(function() {
// First copy the attributes to remove.
var attributes = $.map(this.attributes, function(item) {
return item.name;
});
// Now remove the attributes
var font = $(this);
$.each(attributes, function(i, item) {
$("font").removeAttr(item);
});
});
Looking forward to 1.7 which promises to include a method to remove multiple attributes by name.
One-liner.
For jQuery users
$('img').removeAttr(Object.values($('img').get(0).attributes).map(attr => attr.name).join(' '));
One don't need to refer to the name of attribute to to id nowadays, since we have
removeAttributeNode method.
while(elem.attributes.length > 0) {
elem.removeAttributeNode(elem.attributes[0]);
}
I don't know exactly what you're using it for, but have you considered using css classes instead and toggling those ? It'll be less coding on your side and less work for the browser to do. This will probably not work [easily] if you're generating some of the attributes on the fly like with and height.
This will remove all attributes and it will work for every type of element.
var x = document.createElement($("#some_id").prop("tagName"));
$(x).insertAfter($("#some_id"));
$("#some_id").remove();
Today I have same issue. I think that it will be useful for you
var clone = $(node).html();
clone = $('<tr>'+ clone +'</tr>');
clone.addClass('tmcRow');

How can i get every "a" tag which "href" attribute contain word "youtube"?

I want to catch every a tag which href attribute contain word youtube.
I need to use jquery.
$('a[href*="youtube"]')
For more selectors, see the Selectors portion of the jQuery API.
Attribute Contains Selector:
$('a[href*="youtube"]');
You can always use "filter":
var allYoutubes = $('a').filter(function() { return /youtube/.test(this.href); });
You could use a fancier selector, but this is simple and clear and possibly faster, as the library doesn't need to do the work of figuring out what your selector means. It's a matter of taste mostly.
pretty simple...
$('a[href*="youtube"]')
http://api.jquery.com/attribute-contains-selector/
http://api.jquery.com/category/selectors/
These other answers are great; but in case you're interested it's not that difficult to do a pure JS (no jQuery) alternative
function getYouTubeLinks() {
var links = document.getElementsByTagName("a");
var ytlinks = [];
for(var i=0,l=links.length;i<l;i++){
if(links[i].href.replace("http://","").indexOf("youtube.com") === 0) {
ytlinks.push(links[i]);
}
}
return ytlinks;
}
var youtube = getYouTubeLinks();
for(var i=0,l=youtube.length;i<l;i++){
youtube[i].style.color = "pink";
}
it'd be a good idea to make sure to strip out "www." and "https://" as well.

getElementsByName in IE7

I have some code doing this :
var changes = document.getElementsByName(from);
for (var c=0; c<changes.length; c++) {
var ch = changes[c];
var current = new String(ch.innerHTML);
etc.
}
This works fine in FF and Chrome but not in IE7. Presumably because getElementsByName isn't working in IE. What's the best workaround?
In case you don't know why this isn't working in IE, here is the MSDN documentation on that function:
When you use the getElementsByName method, all elements in the document that have the specified NAME attribute or ID attribute value are returned.
Elements that support both the NAME attribute and the ID attribute are included in the collection returned by the getElementsByName method, but elements with a NAME expando are not included in the collection; therefore, this method cannot be used to retrieve custom tags by name.
Firefox allows getElementsByName() to retrieve elements that use a NAME expando, which is why it works. Whether or not that is a Good Thing™ may be up for debate, but that is the reality of it.
So, one option is to use the getAttribute() DOM method to ask for the NAME attribute and then test the value to see if it is what you want, and if so, add it to an array. This would require, however, that you iterate over all of the nodes in the page or at least within a subsection, which wouldn't be the most efficient. You could constrain that list beforehand by using something like getElementsByTagName() perhaps.
Another way to do this, if you are in control of the HTML of the page, is to give all of the elements of interest an Id that varies only by number, e.g.:
<div id="Change0">...</div>
<div id="Change1">...</div>
<div id="Change2">...</div>
<div id="Change3">...</div>
And then have JavaScript like this:
// assumes consecutive numbering, starting at 0
function getElementsByModifiedId(baseIdentifier) {
var allWantedElements = [];
var idMod = 0;
while(document.getElementById(baseIdentifier + idMod)) { // will stop when it can't find any more
allWantedElements.push(document.getElementById(baseIdentifier + idMod++));
}
return allWantedElements;
}
// call it like so:
var changes = getElementsByModifiedId("Change");
That is a hack, of course, but it would do the job you need and not be too inefficient compare to some other hacks.
If you are using a JavaScript framework/toolkit of some kind, you options are much better, but I don't have time to get into those specifics unless you indicate you are using one. Personally, I don't know how people live without one, they save so much time, effort and frustration that you can't afford not to use one.
There are a couple of problems:
IE is indeed confusing id="" with name=""
name="" isn't allowed on <span>
To fix, I suggest:
Change all the name="" to class=""
Change your code like this:
-
var changes = document.getElementById('text').getElementsByTagName('span');
for (var c=0; c<changes.length; c++) {
var ch = changes[c];
if (ch.className != from)
continue;
var current = new String(ch.innerHTML);
It's not very common to find elements using the NAME property. I would recommend switching to the ID property.
You can however find elements with a specific name using jQuery:
$("*[name='whatevernameYouWant']");
this will return all elements with the given name.
getElementsByName is supported in IE, but there are bugs. In particular it returns elements whose ‘id’ match the given value, as well as ‘name’. Can't tell if that's the problem you're having without a bit more context, code and actual error messages though.
In general, getElementsByName is probably best avoided, because the ‘name’ attribute in HTML has several overlapping purposes which can confuse. Using getElementById is much more reliable. When specifically working with form fields, you can more reliably use form.elements[name] to retrieve the fields you're looking for.
I've had success using a wrapper to return an array of the elements. Works in IE 6, and 7 too. Keep in mind it's not 100% the exact same thing as document.getElementsByName, since it's not a NodeList. But for what I need it for, which is to just run a for loop on an array of elements to do simple things like setting .disabled = true, it works well enough.
Even though this function still uses getElementsByName, it works if used this way. See for yourself.
function getElementsByNameWrapper(name) {
a = new Array();
for (var i = 0; i < document.getElementsByName(name).length; ++i) {
a.push(document.getElementsByName(name)[i]);
}
return a;
}
Workaround
var listOfElements = document.getElementsByName('aName'); // Replace aName with the name you're looking for
// IE hack, because it doesn't properly support getElementsByName
if (listOfElements.length == 0) { // If IE, which hasn't returned any elements
var listOfElements = [];
var spanList = document.getElementsByTagName('*'); // If all the elements are the same type of tag, enter it here (e.g.: SPAN)
for(var i = 0; i < spanList.length; i++) {
if(spanList[i].getAttribute('name') == 'aName') {
listOfElements.push(spanList[i]);
}
}
}
Just another DOM bug in IE:
Bug 1: Click here
Bug 2: Click here

Categories