getElementByName & Regex - javascript

How do I loop through all elements using regular expression in getElementByName?

If you mean like:
var elementArray = document.getElementsByName("/regexhere/");
then no that would not be possible.
To do what you want to do you would have to get all the elements, then go through each one and check the name of it.
Heres a function that will go through all the elements and add all the elements with a certain name to an array:
function findElements(name)
{
var elArray = [];
var tmp = document.getElementsByTagName("*");
var regex = new RegExp("(^|\\s)" + name + "(\\s|$)");
for ( var i = 0; i < tmp.length; i++ ) {
if ( regex.test(tmp[i].name) ) {
elArray.push(tmp[i]);
}
}
return elArray;
}
And use as:
var elName = "customcontrol";
var elArray = customcontrol(elName);
Or it might be easier by className
function findElements(className)
{
var elArray = [];
var tmp = document.getElementsByTagName("*");
var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
for ( var i = 0; i < tmp.length; i++ ) {
if ( regex.test(tmp[i].className) ) {
elArray.push(tmp[i]);
}
}
return elArray;
}
And use as:
var elClassName = "classname";
var elArray;
if (!document.getElementsByClassName)
{
elArray= findElements(elClassName );
}
else
{
elArray = document.getElementsByClassName(elClassName);
}
This would do what you want, without the need for getElementByName.
Although I think you meant getElementsByName
If you wanted to look for an element with only the name "customcontrol" you would use:
var regex = new RegExp("(^|\\s)" + name + "(\\s|$)");
If you wanted to look for an element with that STARTED with the name "customcontrol" you would use:
var regex = new RegExp("(^|\\s)" + name);
EDIT:
If your using jQuery, which would be easier, then this would do:
var elArray = $("*[name^='customcontrol']");
//Use JavaScript to loop through
for (var a = 0; a< elArray.length;a++)
{
//Loop through each element
alert(elArray[a]);
}
//Or
$("*[name^='customcontrol']").css("color","red"); //Or whatever you want to do to the elements

Use a custom selector in jQuery. You probably want an example with parameters.

Related

When i try to compile typescript code into javascript, getting **Type 'NodeListOf<Element>' is not an array type or a string type**

When i try to compile typescript code into javascript, getting Type 'NodeListOf' is not an array type or a string type.
if (query.length) {
var regex = new RegExp("(" + query + ")", "gm");
var li = document.querySelectorAll("#id li"); //error
for (var Element of li){
Element.innerHTML = Element.innerHTML.replace(regex, '<span class="classname">$1</span>');
}
}
}
The below compiles fine and I've added comments inline.
let query = '';
if (query.length) {
var pattern = new RegExp("(" + query + ")", "gim");
var li: NodeListOf<Element> = document.querySelectorAll("#test li");
// ES5 does not allow TS iteration of NodeListOf<Element> nor use of Array.from
// so it is necessary to loop over it manually.
// Note that Element is an existing type which caused a conflict with "(var Element of list)".
// It was necessary to rename Element to element.
for (let i = 0; i < li.length; i++) {
let element = li[i];
element.innerHTML = element.innerHTML.replace(pattern, '<span class="target">$1</span>');
}
}
This does also work:
let elements: any = document.querySelectorAll(".class");
for(let ele of elements) {
// do stuff
}
Try this.. will solve the problems.
if (query.length) {
var pattern = new RegExp("(" + query + ")", "gim");
var li = document.querySelectorAll("#test li");
for (var Element of <any> li){
Element.innerHTML = Element.innerHTML.replace(pattern, '<span class="target">$1</span>');
}
}

Find all elements in page by passing class name in javascript function without using getElementsBy* or any lib function

I am trying to find all elements in the page by passing class name in this function, I getting all elements as arrays object but I need only those elements those are having my className only.
var custSearch = function (element, className) {
var elementsArray = [];
// add spaces
var q = ' ' + className + ' ';
(function recFind (node) {
// Looping through all the child nodes
for (var i = 0; i < node.childNodes.length; i++) {
var currentNode = node.childNodes[i];
var currentClass = currentNode.className;
// check if current class match with param class
if ((' '+currentClass+' ').indexOf(q)) {
elementsArray.push(currentNode);
}
currentNode.childNodes && recFind(currentNode);
}
})(element);
return elementsArray;
};
custSearch(document, 'spch');
I don't want to use getElementsByClassName function but I want similar result, this above function should give me exact result but I am not finding what I am doing wrong, Can someone tell me if I am making any logical error?
HTML is like this
<div class="spch s2fp-h" style="display:none" id="spch"><div class="spchc" id="spchc"><div class="_o3"><div class="_AM"><span class="_CMb" id="spchl"></span><span class="button" id="spchb"><div class="_wPb"><span class="_AUb"></span><div class="_Fjd"><span class="_oXb"></span><span class="_dWb"></span></div></div></span></div><div class="_gjb"><span class="spcht" id="spchi" style="color:#777"></span><span class="spcht" id="spchf" style="color:#000"></span></div><div class="google-logo"></div></div><div class="_ypc"><div class="_zpc"></div></div></div><div class="close-button" id="spchx">×</div></div>
Try the following:
function myGetElementsByClassName(className) {
var nodes = document.getElementsByTagName('*');
var out = [];
for( var i=0, len=nodes.length; i<len; i++) {
if( nodes[i].classList.contains( className ) ) {
out.push( nodes[i] );
}
}
return out;
}

Find all elements whose id begins with a common string

I have a XSL that created multiple elements with the id of "createdOn" plus a $unique-id
Example : createdOnid0xfff5db30
I want to find and store these in a variable using JavaScript. I've tried
var dates = document.getElementsById(/createdOn/);
but that doesn't appear to work.
Using jQuery you can use the attr starts with selector:
var dates = $('[id^="createdOnid"]');
Using modern browsers, you can use the CSS3 attribute value begins with selector along with querySelectorAll:
var dates = document.querySelectorAll('[id^="createdOnID"]');
But for a fallback for old browsers (and without jQuery) you'll need:
var dateRE = /^createdOnid/;
var dates=[],els=document.getElementsByTagName('*');
for (var i=els.length;i--;) if (dateRE.test(els[i].id)) dates.push(els[i]);
You should have just used simple CSS selector together with JavaScript's .querySelectorAll() method.
In your case :
var dates = document.querySelectorAll('[id^="createdOnId"]');
Because you didn't tag jQuery, and you probably don't need it, my suggestion would be to add a class to these elements when you create them. Then use the getElementsByClassName() function that's built into most browsers. For IE you would need to add something like this:
if (typeof document.getElementsByClassName!='function') {
document.getElementsByClassName = function() {
var elms = document.getElementsByTagName('*');
var ei = new Array();
for (i=0;i<elms.length;i++) {
if (elms[i].getAttribute('class')) {
ecl = elms[i].getAttribute('class').split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
} else if (elms[i].className) {
ecl = elms[i].className.split(' ');
for (j=0;j<ecl.length;j++) {
if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
ei.push(elms[i]);
}
}
}
}
return ei;
}
}
function idsLike(str){
var nodes= document.body.getElementsByTagName('*'),
L= nodes.length, A= [], temp;
while(L){
temp= nodes[--L].id || '';
if(temp.indexOf(str)== 0) A.push(temp);
}
return A;
}
idsLike('createdOn')
Try the following:
var values = new Array(valueKey_1);
var keys = new Array("nameKey_1");
var form = document.forms[0];
for (var i = 0; i < form.length; i++) {
name = form.elements[i].name;
var startName = name.toLowerCase().substring(0, 18);
if (startName == 'startStringExample') {
values.push(name.value);
keys.push(name);
}
}

Why is my Javascript not valid?

I have a div with ID 'adpictureholder', to which I dynamically add (or remove) images.
On Form submit I want to get SRC values of all these images within that DIV and put them to the value of one hidden input with ID 'piclinkslisttosubmit'. The thing is that my current Javascript does not function as if there is some syntax typo there, but I don't see where. Can anyone please have a quick look at it?
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes[].length - 1;
var images = document.getElementById('adpictureholder').childNodes[];
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
}
Change childNodes[] to simply childNodes.
You don't need to specify that a variable you're referencing is an array by adding brackets.
Your javascript isn't valid because you keep putting childNodes[] you can solve that by replacing childNodes[] with simply childNodes
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes.length - 1;
var images = document.getElementById('adpictureholder').childNodes;
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
} ​
You shouldn't use [] when reading a property value:
var images = document.getElementById('adpictureholder').childNodes;
You can then get the length from the array, instead of reading the property again:
var endi = images.length - 1;
First off you don't need the [] after childNodes. that causes an error.
You also were forgetting that childNodes includes text nodes and would not work properly, because they did not all contain the src property. I've corrected that in the following example:
function copyonsubmit() {
var str = '';
var textbox = document.getElementById('piclinkslisttosubmit');
var i = 0;
var images = document.getElementById('adpictureholder').childNodes;
var numImages = images.length - 1;
var src = "";
for (i = 0; i < numImages; i++) {
if (images[i].tagName === "IMG") {
str += images[i].src + '|';
}
}
str = str.slice(0, -1); // cut off the final |
textbox.value = str;
}
http://jsfiddle.net/NWArL/2/
Secondly you could write this really simply with jQuery.
var str = "";
$("#apictureholder").children("img").each(function() {
str += $(this).attr("src") + "|";
})
$("#piclinkslisttosubmit").val(str);
Third off make sure to check your console for errors. It was very clear when I ran this code on JSFiddle that it had a problem.
Finally, what exactly are you trying to do?
Change childNodes[] to childNodes and rest looks fine to me,
Read about childNodes
Try,
function copyonsubmit(){
var strump1 = '';
var i=0;
var endi = document.getElementById('adpictureholder').childNodes.length - 1;
var images = document.getElementById('adpictureholder').childNodes;
for (i=0;i<=endi;i++)
{
strump1 = strump1 + '|' + images[i].src;
}
document.getElementById('piclinkslisttosubmit').value = strump1;
}
You said you were using jQuery, but you presented us with vanilla Javascript. I took the liberty of converting your code to jQuery and cleaning it up a bit. The others have already identified your problem, though.
function copyonsubmit() {
var strump1 = '';
var images = $("#adpictureholder")[0].childNodes;
for (var i = 0; i < images.length; i++) {
strump1 += '|' + images[i].src;
}
$('#piclinkslisttosubmit').val(strump1);
}​

Get the list of attributes of a HTML string using Javascript

How can I get the list of attributes of an HTML string using Javascript? Here's my code so far.
function traverse_test(){
var root=document.getElementById('arbre0').childNodes;
for(var i=0;i<root.length;i++){
var lis = root[i];
if (lis =='[object HTMLUListElement]') {
for (var member in lis) {
if (typeof lis[member] == "string") {
var assertion = lis[member];
var resultat = assertion.search(/..Bookmarks/);
if (resultat != -1) {
output.innerHTML+= lis[member];
// Here I'd like to have the list of lis[member] attributes
for(var attr in lis[member].attributes) {
output.innerHTML+=lis[member].attributes[attr].name + "=\""+ lis[member].attributes[attr].value + "\"";
}
break;
}
}
}
}
}
}
Use the Node.attributes property of a DOM element. Example:
var foo = document.getElementById('foo'),
attrs = foo.attributes,
i = attrs.length,
attr;
while (i--)
{
attr = attrs[i];
console.log(attr.name + '="' + attr.value + '"');
}
Demo: http://jsfiddle.net/mattball/j8AVq/
Seems like all these answers point to how to get an attr list from a node but the question asks for attrs from an HTML string. Here is my 2cents.
//turn your string into a node and get your html strings NamedNodeMap
var temp = document.createElement("div");
temp.innerHTML = "<div attr-1 attr-2 attr-3 attr-4></div>";
temp = temp.firstElementChild.attributes;
//put the attributes in a an array
var list = Object.keys(temp).map( function( index ) { return temp[ index ] } );
console.log( list );
If you know the attributes to get the value you can do:
var MyValue = document.getElementById("myimage").getAttribute("src")
In JavaScript to loop all attributes:
var el = document.getElementById("someId");
var arr = [];
for (var i=0, attrs=el.attributes, l=attrs.length; i<l; i++){
arr.push(attrs.item(i).nodeName);
}
The above code was taken from this question
Jquery might be another option:
http://plugins.jquery.com/project/getAttributes
[].slice
.apply(document.querySelector('something').attributes)
.forEach(function(item){
console.log(item, item.name, item.value);
});

Categories

Resources