Using regex incremental numbers in javascript - javascript

I'm trying to hide elements by their ids:
document.getElementById('Table1').style.display = 'none';
But there are many divs goes like Table1, Table2, Table3...
So how to use regular expressions in a situation like this?

Set class to all these elements. It was invented for such cases.
HTML:
<div id="Table1" class="myTables"></div>
<div id="Table2" class="myTables"></div>
<div id="Table3" class="myTables"></div>
JavaScript:
var elements = document.getElementsByClassName("myTables");
for (var i = 0, len = elements.length; i < len; i++) {
elements[i].style.display = "none";
}
UPDATE: If setting classes is not applicable in your case, you can always use the modern method querySelectorAll with attribute starts with selector:
var elements = document.querySelectorAll("div[id^='Table']");
for (var i = 0, len = elements.length; i < len; i++) {
elements[i].style.display = "none";
}
DEMO: http://jsfiddle.net/L2de8/

Regural expression will not work in this example.
Either use a common class name on all the elements, or, if you cannot change HTML, you can use Selectors API to select the elements you need to hide.
Use
var allElemsWithIdStartingFromTable = document.querySelectorAll('[id^="Table"]');
to select all elements with ID starting with "Table", so it would be Table1, Table2, but also TableOfProducts, keep that in mind.
Then you need to iterate over this and check if the id attribute matches /^Table\d+$/ regular expression.

for example..if you give myTables as class name for div..use that for lenght..
var elements = document.getElementsByClassName("myTables");//to know the length only..
for(var i=0;i<elements.length;i++)
{
document.getElementById('Table'+i).style.display = 'none';
}
use looping concept..its an example..

Related

How to get ALL id's inside of a DIV using pure javascript

I want to get every single ID of every element inside of a Div at once, and change all of their class names. Like:
<div id = "container">
<div id = "alot"></div>
<div id = "of"></div>
<div id = "random"></div>
<div id = "ids"></div>
</div>
<script>
var everyId = //all of the ids in #container. but how ?
document.getElementById( everyId ).className = "anything";
</script>
I've seen solutions using libraries but Is this possible with pure Javascript?
Try something like this:
var ids = [];
var children = document.getElementById("container").children; //get container element children.
for (var i = 0, len = children.length ; i < len; i++) {
children[i].className = 'new-class'; //change child class name.
ids.push(children[i].id); //get child id.
}
console.log(ids);
Leverage document.querySelectorAll() and a loop to achieve what you're looking for:
var everyChild = document.querySelectorAll("#container div");
for (var i = 0; i<everyChild.length; i++) {
everyChild[i].classList.add("anything");
}
JSFiddle
You can leverage querySelectorAll to provide a selector to fetch the elements you are interested in.
var c = document.querySelectorAll("#container > div");
console.log(c); // array of all children div below #container
You can use querySelectorAll for the Child elements within the specified parent:
var a = document.querySelectorAll('#container > div'); // get all children within container
console.log(a);
for (var i = 0; i<a.length; i++){ // loop over the elements
console.log(a[i].id); // get the ids
a[i].className = 'newClass'; // change the class names
}

Access dynamic generated div id

I have some div ids that are generated dynamicly via php
<div id='a<?php echo $gid?>>
How can I access them in JavaScript? All these divs start with "A" followed by a number.
Is there some kind of search function
getElementById(a*)?
Thanks for any help
No generic JavaScript function for this (at least not something cross browser), but you can use the .getElementsByTagName and iterate the result:
var arrDivs = document.getElementsByTagName("div");
for (var i = 0; i < arrDivs.length; i++) {
var oDiv = arrDivs[i];
if (oDiv.id && oDiv.id.substr(0, 1) == "a") {
//found a matching div!
}
}
This is the most low level you can get so you won't have to worry about old browsers, new browsers or future browsers.
To wrap this into a neater function, you can have:
function GetElementsStartingWith(tagName, subString) {
var elements = document.getElementsByTagName(tagName);
var result = [];
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
if (element.id && element.id.substr(0, subString.length) == subString) {
result.push(element);
}
}
return result;
}
The usage example would be:
window.onload = function() {
var arrDivs = GetElementsStartingWith("div", "a");
for (var i = 0; i < arrDivs.length; i++) {
arrDivs[i].style.backgroundColor = "red";
}
};
Live test case.
In case you choose to use jQuery at some point (not worth for this thing alone) all the above code turns to single line:
$(document).ready(function() {
$('div[id^="a"]').css("background-color", "blue");
});
Updated fiddle, with jQuery.
No, you need a fixed id value for getElementById to work. However, there are other ways to search the DOM for elements (e.g. by CSS classes).
You can use querySelectorAll to get all divs that have an ID starting with a. Then check each one to see if it contains a number.
var aDivs = document.querySelectorAll('div[id^="a"]');
for(var index = 0, len = aDivs.length; index < len; index++){
var aDiv = aDivs[index];
if(aDiv.id.match(/a\d+/)){
// aDiv is a matching div
}
}​
DEMO: http://jsfiddle.net/NTICompass/VaTMe/2/
Well, I question myself why you would need to select/get an element, that has a random ID. I would assume, you want to do something with every div that has a random ID (like arranging or resizing them).
In that case -> give your elements a class like "myGeneratedDivs" with the random ID (if you need it for something).
And then select all with javascript
var filteredResults=document.querySelectorAll(".myGeneratedDivs").filter(function(elem){
....
return true;
});
or use jQuery/Zepto/YourWeaponOfChoice
var filteredResults=$(".myGeneratedDivs").filter(function(index){
var elem=this;
....
return true;
});
If you plan to use jQuery, you can use following jQuery selectors
div[id^="a"]
or
$('div[id^="id"]').each(function(){
// your stuff here
});
You will have to target the parent div and when someone click on child div inside a parent div then you can catch the child div.
<div id="target">
<div id="tag1" >tag1</div>
<div id="tag1" >tag2</div>
<div id="tag1" >tag3</div>
</div>
$("#target").on("click", "div", function() {
var showid = $(this).attr('id');
alert(showid)
});
getElementById() will return the exact element specified. There are many javascript frameworks including jQuery that allow much more powerful selection capabilities. eg:
Select an element by id: $("#theId")
Select a group of elements by class: $(".class")
Select subelements: $("ul a.action")
For your specific problem you could easily construct the appropriate selector.

How to hide all divs with JavaScript?

I am wondering how I can hide all divs on the page only using JavaScript, I cannot use jQuery. Is there a way to do this without using the arrays that comes with document.getElementByTag? Or if there is not, could you show me how to hide all?
Use getElementsByTagName() to get a list of all div elements, and then set their CSS display property to none:
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
divs[i].style.display = 'none';
}
<div>sads</div>
<div>sads</div>
<span>not a div</span>
You will need to use document.getElementsByTagName, and then use a for loop to process all of the elements:
var divs = document.getElementsByTagName('div');
for(var i = 0; i < divs.length; i++) {
divs[i].style.display = "none";
}
Just to put out a totally different solution here.
You could set a CSS class to your body, like this
body.hideDivs DIV {
display: none;
}
document.body.className = "hideDivs";
But this would hide everything inside those divs also, which might not be what you are going for here.

Javascript - Link Name Changing with restrictions

I'm trying to change the name of a link, however, I have some restrictions. The link is placed in code that looks like this:
<li class='time'>
Review Time
<img alt="Styled" src="blah" />
</li>
Basically, I have a class name to work with. I'm not allowed to edit anything in these lines, and I only have a header/footer to write Javascript / CSS in. I'm trying to get Review Time to show up as Time Review, for example.
I know that I can hide it by using .time{ display: hide} in CSS, but I can't figure out a way to replace the text. The text is also a link, as shown. I've tried a variety of replace functions and such in JS, but I'm either doing it wrong, or it doesn't work.
Any help would be appreciated.
You could get the child elements of the li that has the class name you are looking for, and then change the innerHTML of the anchor tags that you find.
For example:
var elements = document.getElementsByClassName("time")[0].getElementsByTagName("a");
for(var i = 0, j = elements.length; i<j; i++){
elements[i].innerHTML = "Time Review";
}
Of course, this assumes that there is one element named "time" on the page. You would also need to be careful about checking for nulls.
Split the words on space, reverse the order, put back together.
var j = $('li.time > a');
var t = j.text();
var a = t.split(' ');
var r = a.reverse();
j.text(r.join(' '));
This could have some nasty consequences in a multilingual situation.
Old school JavaScript:
function replaceLinkText(className, newContents) {
var items = document.getElementsByTagName('LI');
for (var i=0; i<items.length; i++) {
if (items[i].className == className) {
var a = items[i].getElementsByTagName('A');
if (a[0]) a[0].innerHTML = newContents;
}
}
}
replaceLinkText("time", "Review Time");
Note that modern browsers support getElementsByClassName(), which could simplify things a bit.
You can traverse the DOM and modify the Text with the following JavaScript:
var li = document.getElementsByClassName('time');
for (var i = 0; i < li.length; i++) {
li[i].getElementsByTagName('a')[0].innerText = 'new text';
}
Demo: http://jsfiddle.net/KFA58/

How to get all elements inside "div" that starts with a known text

I have a div element in an HTML document.
I would like to extract all elements inside this div with id attributes starting with a known string (e.g. "q17_").
How can I achieve this using JavaScript ?
If needed, for simplicity, I can assume that all elements inside the div are of type input or select.
var matches = [];
var searchEles = document.getElementById("myDiv").children;
for(var i = 0; i < searchEles.length; i++) {
if(searchEles[i].tagName == 'SELECT' || searchEles.tagName == 'INPUT') {
if(searchEles[i].id.indexOf('q1_') == 0) {
matches.push(searchEles[i]);
}
}
}
Once again, I strongly suggest jQuery for such tasks:
$("#myDiv :input").hide(); // :input matches all input elements, including selects
Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :
var elements = document.getElementById('parentContainer').children;
Option 2: Likely slowest :
var elements = document.getElementById('parentContainer').getElementsByTagName('*');
Option 3: Requires change to code (wrap a form instead of a div around it) :
// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;
var matches = [];
for (var i = 0; i < elements.length; i++)
if (elements[i].value.indexOf('q17_') == 0)
matches.push(elements[i]);
With modern browsers, this is easy without jQuery:
document.getElementById('yourParentDiv').querySelectorAll('[id^="q17_"]');
The querySelectorAll takes a selector (as per CSS selectors) and uses it to search children of the 'yourParentDiv' element recursively. The selector uses ^= which means "starts with".
Note that all browsers released since June 2009 support this.
Presuming every new branch in your tree is a div, I have implemented this solution with 2 functions:
function fillArray(vector1,vector2){
for (var i = 0; i < vector1.length; i++){
if (vector1[i].id.indexOf('q17_') == 0)
vector2.push(vector1[i]);
if(vector1[i].tagName == 'DIV')
fillArray (document.getElementById(vector1[i].id).children,vector2);
}
}
function selectAllElementsInsideDiv(divId){
var matches = new Array();
var searchEles = document.getElementById(divId).children;
fillArray(searchEles,matches);
return matches;
}
Now presuming your div's id is 'myDiv', all you have to do is create an array element and set its value to the function's return:
var ElementsInsideMyDiv = new Array();
ElementsInsideMyDiv = selectAllElementsInsideDiv('myDiv')
I have tested it and it worked for me. I hope it helps you.
var $list = $('#divname input[id^="q17_"]'); // get all input controls with id q17_
// once you have $list you can do whatever you want
var ControlCnt = $list.length;
// Now loop through list of controls
$list.each( function() {
var id = $(this).prop("id"); // get id
var cbx = '';
if ($(this).is(':checkbox') || $(this).is(':radio')) {
// Need to see if this control is checked
}
else {
// Nope, not a checked control - so do something else
}
});
i have tested a sample and i would like to share this sample and i am sure it's quite help full.
I have done all thing in body, first creating an structure there on click of button you will call a
function selectallelement(); on mouse click which will pass the id of that div about which you want to know the childrens.
I have given alerts here on different level so u can test where r u now in the coding .
<body>
<h1>javascript to count the number of children of given child</h1>
<div id="count">
<span>a</span>
<span>s</span>
<span>d</span>
<span>ff</span>
<div>fsds</div>
<p>fffff</p>
</div>
<button type="button" onclick="selectallelement('count')">click</button>
<p>total element no.</p>
<p id="sho">here</p>
<script>
function selectallelement(divid)
{
alert(divid);
var ele = document.getElementById(divid).children;
var match = new Array();
var i = fillArray(ele,match);
alert(i);
document.getElementById('sho').innerHTML = i;
}
function fillArray(e1,a1)
{
alert("we are here");
for(var i =0;i<e1.length;i++)
{
if(e1[i].id.indexOf('count') == 0)
a1.push(e1[i]);
}
return i;
}
</script>
</body>
USE THIS I AM SURE U WILL GET YOUR ANSWER ...THANKS

Categories