Editing all external links with javascript - javascript

How can I go through all external links in a div with javascript, adding (or appending) a class and alt-text?
I guess I need to fetch all objects inside the div element, then check if each object is a , and check if the href attributen starts with http(s):// (should then be an external link), then add content to the alt and class attribute (if they don't exist create them, if they do exists; append the wanted values).
But, how do I do this in code?

This one is tested:
<style type="text/css">
.AddedClass
{
background-color: #88FF99;
}
</style>
<script type="text/javascript">
window.onload = function ()
{
var re = /^(https?:\/\/[^\/]+).*$/;
var currentHref = window.location.href.replace(re, '$1');
var reLocal = new RegExp('^' + currentHref.replace(/\./, '\\.'));
var linksDiv = document.getElementById("Links");
if (linksDiv == null) return;
var links = linksDiv.getElementsByTagName("a");
for (var i = 0; i < links.length; i++)
{
var href = links[i].href;
if (href == '' || reLocal.test(href) || !/^http/.test(href))
continue;
if (links[i].className != undefined)
{
links[i].className += ' AddedClass';
}
else
{
links[i].className = 'AddedClass';
}
if (links[i].title != undefined && links[i].title != '')
{
links[i].title += ' (outside link)';
}
else
{
links[i].title = 'Outside link';
}
}
}
</script>
<div id="Links">
<a name="_Links"></a>
FOO
FILE
SomeWhere
SomeWhere 2
SomeWhere 3
ElseWhere 1
ElseWhere 2
ElseWhere 3
BAR
Show/Hide
</div>
If you are on an account on a shared server, like http://big-server.com/~UserName/, you might want to hard-code the URL to go beyond the top level. On the other hand, you might want to alter the RE if you want http://foo.my-server.com and http://bar.my-server.com marked as local.
[UPDATE] Improved robustness after good remarks...
I don't highlight FTP or other protocols, they probably deserve a distinct routine.

I think something like this could be a starting point:
var links = document.getElementsByTagName("a"); //use div object here instead of document
for (var i=0; i<links.length; i++)
{
if (links[i].href.substring(0, 5) == 'https')
{
links[i].setAttribute('title', 'abc');
links[i].setAttribute('class', 'abc');
links[i].setAttribute('className', 'abc');
}
}
you could also loop through all the A elements in the document, and check the parent to see if the div is the one you are looking for

This can be accomplished pretty easily with Jquery. You would add this to the onload:
$("div a[href^='http']").each(function() {
$(this).attr("alt",altText);
var oldClassAttributeValue = $(this).attr("class");
if(!oldClassAttributeValue) {
$(this).attr("class",newClassAttributeValue);
}
});
You could modify this to add text. Class can also be modified using the css function.

My (non-framework) approach would be something along the lines of:
window.onload = function(){
targetDiv = document.getElementById("divName");
linksArray = targetDiv.getElementsByTagName("a");
for(i=0;i=linksArray.length;i++){
thisLink = linksArray[i].href;
if(thisLink.substring(4,0) = "http"){
linksArray[i].className += "yourcontent"; //you said append so +=
linksArray[i].alt += "yourcontent";
}
}
}
This is not tested but I would start like this and debug it from here.

Related

Make text into links outside of <a> tags only

Here's my issue. I made a function that resolves links in javascript, but the use-case I'm stuck with is that there may already be HTML in posts with links.
Users can not post true HTML, but moderators and administrators can, meaning I need to handle both cases.
Here's an example of your typical user post HTML:
<div class="teaser">
This is just your normal post http://google.com some other stuff
</div>
And administrator/moderator:
<div class="teaser">
<b>
THIS LINK
</b>
<br><br>
Supplemental reading: Link again
</div>
Normally, I'd use something like
function replaceURLWithHTMLLinks(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
return text.replace(exp,"<a href='$1' target='_blank'>$1</a>");
}
c.not('a').each(function() {
var html = $(this).html();
$(this).html(replaceURLWithHTMLLinks(html));
});
But this causes links to be parsed which exist inside of the href property. I need to be able to create links only when they are outside of tags, and it needs to be through all children as you'll notice that is the first child in a mod/admin post (if they so choose).
Mods and admins can put basically any HTML they desire in their posts, so the tag could be anywhere in the post hierarchy which is not at all consistent.
I could just not parse links on admin or mod posts, but sometimes some mods and admins use the proper HTML tags, and sometimes they don't, which is why I'd like to know the proper way of doing this.
Try this:
var exp = /^(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
$('.teaser').each(function() {
var i, words;
$this = $(this);
words = $this.html().split(' ');
for (i = 0; i < words.length; i++) {
if (exp.test(words[i])) {
words[i] = words[i].replace(exp, "<a href='$1' target='_blank'>$1</a>");
}
}
$this.html(words.join(' '));
});
Demo Link
I found the answer here it seems.
filterTeaserLinkContent: function(data) {
var exp = /\b((https?|ftps?|about|bitcoin|git|irc[s6]?):(\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/|magnet:\?(dn|x[lts]|as|kt|mt|tr)=)([^\s()<>]+|\([^\s()<>]+\))+(\([^\s()<>]+\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])/g;
var nodes = data[0].childNodes;
for(var i = 0; i < nodes.length; i++) {
var n = nodes[i];
if(n.nodeType == n.TEXT_NODE || n.nodeName == 'BR') {
var g = n.textContent.match(exp);
while(g) {
var idx=n.textContent.indexOf(g[0]);
var pre=n.textContent.substring(0,idx);
var a=document.createElement("a");
if (!/^[a-z][\w-]+:/.test(g[0])) {
a.href = "http://" + g[0];
} else {
a.href = g[0];
}
a.innerText = g[0];
n.textContent = n.textContent.substring(idx+g[0].length);
n.parentElement.insertBefore(a,n);
g=n.textContent.match(exp);
}
} else {
Board.filterTeaserLinkContent($(n));
}
}
},
filterTeaserContent: function(data) {
// Jam into <div> so we can play with it
var c = $('<div>' + data + '</div>');
// Remove <wbr> tag which breaks links
c.find('wbr').each(function() {
$(this).remove();
});
// Re-parse the HTML after removing <wbr> or else the text nodes won't be joined
c = $('<div>' + c.html() + '</div>');
// I actually forget what this does, but fuck it. Shit.
c.not("div, s, span, a").each(function() {
var content = $(this).contents();
$(this).replaceWith(content);
});
Board.filterTeaserLinkContent(c);
// Remove images in post preview because they don't need to be here...
c.find('img').each(function() {
$(this).remove();
});
// Simplify line breaks
return c.html().replace(/<br ?\/?><br ?\/?>/g, "<br>");
},
This is for use in the 4chan API in case anyone was curious.

Removing JavaScript from a link

The link's code is as follows:
<td class="buttonColumn">
Leave to Google
</td>
<td class="buttonColumn">
Leave to Yahoo
</td>
There are multiple buttons on the page with the exact same format that need to be changed as well. I was thinking something like this:
var fix = document.getElementsByClassName('actionButtonNew');
for (var i=0; i<fix.length; i++) {
I am not sure how to finish the code. I tried this:
var fix = document.getElementsByClassName('actionButtonNew');
for(var i = 0; i < fix.length; i++) {
try {
var l = fix[i];
var h = fix[i].parentNode.getElementsByClassName('actionButtonNew')[0].href.replace("javascript:confirmDialog('Are you sure you want to go?',", "");
l.href = h;
} catch(e) {}
}
I know it is very messy and bad. It does change the link to: 'http://google.com');
So I think I may be on the right track. Please help me. Thanks in advance!
Here's an idea: rather than deal with messy regular expressions that are bound to break on some edge case, replace confirmDialog with a function that redirects without confirming:
window.noConfirm = function(m, url) {
document.location.href = url;
}
var fix = document.getElementsByClassName('actionButtonNew');
for (var i = 0; i < fix.length; i++) {
fix[i].href = fix[i].href.replace('confirmDialog', 'noConfirm');
}
http://jsfiddle.net/AV4tB/
And another funny idea: change it call a function that immediately fixes the link, then trigger a click:
window.fixMe = function(m, url) {
this.href = url;
}
var linksToFix = document.getElementsByClassName('actionButtonNew');
for (var i = 0; i < linksToFix.length; i++) {
window.a = linksToFix[i];
linksToFix[i].href = linksToFix[i].href.replace('confirmDialog(', 'fixMe.call(a, ');
linksToFix[i].click();
}
http://jsfiddle.net/AV4tB/1/
Try this:
var fix = document.getElementsByClassName('actionButtonNew');
for (var i = 0; i < fix.length; i++) {
fix[i].href = fix[i].href.replace(/javascript:confirmDialog\(\'Are you sure you want go\?\'\, \'(http\:\/\/.*\.(.){2,3})'\);/gi,'$1');
}
Which uses regex to replace the confirm JS with just the links.
E.g. "javascript:confirmDialog('Are you sure you want go?', 'http://yahoo.com');" becomes "http://yahoo.com"
Pretty annoying to say to users "do you really want to do that?" every time they click on a link. After all, the back button will usually bring them straight back, or the escape key will cancel navigation if they're quick.
Since A elements may not all be links (some are targets), you can get all the links in a page using the document.links collection, then iterate over that:
// Function to call
function navPrompt() {
var text = this.textContent || this.innerText
return confirm('Are you sure you want to go to ' + text + '?');
}
// Attach to all listeners
window.onload = function() {
var links = document.links;
var i = links.length;
while (i--) {
links[i].onclick = navPrompt;
}
}
On the otherhand, if you want to remove the comfirm box and change:
href="javascript:confirmDialog('Are you sure you want go?', 'http://google.com');"
to:
href="http://google.com"
you can do:
window.onload = function() {
var link, links = document.links;
var i = links.length;
while (i--) {
link = links[i];
link.href = link.href.replace(/.*(http[^\'\"]+).+/i,'$1');
}
}
Which will strip out the URL and assign it to the href property.

javascript unobtrusive

i have an html page, which is consist of many hyperlink like this inside body tag...
User Name
then i decide to use unobtrusive javascript ... then i'd like to change all the "a" tag to be...
<a id="354313" href=#>User Name</a>
when i click the second link above, i want that it'll call a function like the first link does,...
my question is how to get all the "a" element inside body tag then apply a function depend it's id...
With jQuery, something like this:
$('a').click(function() {
var id = this.getAttribute('id');
// Do something...
});
If you want it to work on all elements ever created, use this:
$('a').live('click', function() {
var id = this.getAttribute('id');
// Do something...
});
I hope this is what you are trying.
<script type='text/javascript'>
var alA = document.getElementsByTagName("a");
for(var aCounter=0;aCounter<alA.length;aCounter++) {
var singleA = alA[aCounter];
singleA.onclick = function () {
window.open = "http://www.example.com/?id="+singleA.id;
}
}
<script>
What you're after is this code:
<script type="text/javascript">
window.onload = function WindowLoad() {
var arrLinks = document.getElementsByTagName("a");
for (var i = 0; i < arrLinks.length; i++) {
var oLink = arrLinks[i];
var sCurHref = oLink.href;
if (sCurHref.indexOf("?id=") >= 0) {
var ID = sCurHref.split("?id=")[1];
if (ID.length > 0) {
oLink.id = ID;
oLink.href = "#";
oLink.onclick = function() {
document.location.href = sCurHref;
return false;
}
}
}
}
}
</script>
This will iterate all the links, changing the visible HREF to "#" and preserving their functionality, applying the proper ID. (Though you didn't say what's the use of that ID)
Feel free to mess around with the live test case: http://jsfiddle.net/yahavbr/uMbEY/
Something like:
<script language="javascript">
function myFunction(id)
{
alert(id);
}
</script>
<a id="354313" onclick="myFunction(this.id);" href="#">;User Name<;/a>
Not sure though Test it :)
I will rather say that add class to the links u want to handle this way
<a class="mylink" ... >User Name </a>
Now read the elements by class name. If you are using new browsers or any JS library like JQuery its great.
var links = document.getElementsByClassName("mylink") //Method in Mozilla Browser
Above are the links that you can process nicely without getting into trouble.
// Function that you want to call
function fake(id)
{
// Your content
}
// Get all "a" elements and put it in an Array
var links = window.document.getElementsByTagName("a");
for (var i=0; i<links.length; ++i)
{
fake(links[i].id);
}

JavaScript | Grab inner HTML Text

Let's say I have this line somewhere in my code:
<ul id="mobileBtnsBot">
<li>
<span class="alertsBtn"></span><span class="btnText">Alerts & Advisories</span><div class="button_last"></div>
</li>
<li>
<span class="schedBtn"></span><span class="btnText">Schedules</span><div class="button_last"></div>
</li>
<li>
<span class="mapsBtn"></span><span class="btnText">Maps & Stations</span><div class="button_last"></div>
</li>
<li>
<span class="trainBtn"></span><span class="btnText">TrainView</span><div class="button_last"></div>
</li>
<li>
<span class="ntaBtn"></span><span class="btnText">Next To Arrive</span><div class="button_last"></div>
</li>
<li>
<span class="faresBtn"></span><span class="btnText">Fares</span><div class="button_last"></div>
</li>
<li>
<span class="mediaBtn"></span><span class="btnText"># SEPTA</span><div class="button_last"></div>
</li>
<li>
<span class="button_beg"></span><span class="btnText">Find my Location</span><div class="button_last"></div>
</li>
</ul>
I want to use JavaScript to find the <a> holding the text Find my location and hide it according to whichever user-agent your on.
I know you are not supposed to use user-agents as such but I can't use any server-side languages.
If anyone knows how to accomplish this or has a better idea, please share.
EDIT: This page is being created from a web form in Alfresco CMS. If I give it an ID they all get the ID.
isBrowser.js
if (navigator.userAgent.indexOf('Gecko')!= -1
|| navigator.userAgent.indexOf('MSIE')!= -1 || navigator.userAgent.indexOf('Opera')!= -1 || navigator.userAgent.indexOf('Chrome')!= -1) {
document.write('<link rel="stylesheet" href="/m/css/smartmobile.css" type="text/css" />');
}
else if (navigator.userAgent.indexOf('webkit')!= -1) {
document.write('<link rel="stylesheet" href="/m/css/smartmobile.css" type="text/css" />');
}
else{
alert("load mobile css");
document.write('<link rel="stylesheet" href="/m/css/mobile.css" type="text/css" />');
function hideListItem(text)
{
var ul = document.getElementById("mobileBtnsBot");
alert("line1");
for(var i = 0; i < ul.childNodes.length; i++)
{
alert("line2-loop");
var li = ul.childNodes[i];
alert("line3-loop");
// Element node.
if (li.nodeType == 1)
{
alert("line4-loop");
// Find the text in all of the inner-html.
if (li.innerHTML.indexOf(text) != -1)
{
alert("line5-loop");
li.style.display = "none";
break;
}
alert("line6-loop");
}
alert("line7-loop");
}
alert("line8");
}
hideListItem("Find my Location");
}
mobile-script.js
window.onload = function () {
setTimeout(function(){window.scrollTo(0, 1);}, 100);
var linkElementLnk = document.getElementById("BackButtonlnk");
linkElementLnk.style.display = 'none';
insert();
}
function insert(){
var linkElement = document.getElementById("BackButton");
var linkElementLnk = document.getElementById("BackButtonlnk");
var loc_array = document.location.href.split('/');
if (loc_array[loc_array.length-3] == "maps"|| loc_array[loc_array.length-2] == "stations" || loc_array[loc_array.length-3] == "stations" )
{
linkElementLnk.style.display = 'block';
var newT = document.createTextNode("Stations & Maps");
}
else if (loc_array[loc_array.length-3] == "m")
{
linkElementLnk.style.display = 'none';
}
else if (loc_array[loc_array.length-3] != "m")
{
linkElementLnk.style.display = 'block';
if (loc_array[loc_array.length-2] == "w" || loc_array[loc_array.length-2] == "s" || loc_array[loc_array.length-2] == "h" )
{
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
}
else
{
if (loc_array[loc_array.length-1] == "index.html" || loc_array[loc_array.length-1] == "index.shtml" || loc_array[loc_array.length-1] == "")
{
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-3])));
}
else
{
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2])));
}
}
}
linkElement.appendChild(newT);
}
function capWords(str){
var words = str.split(" ");
for (var i=0 ; i < words.length ; i++){
var testwd = words[i];
var firLet = testwd.substr(0,1);
var rest = testwd.substr(1, testwd.length -1)
words[i] = firLet.toUpperCase() + rest
}
return words;
}
Here's a nice short one.
function findLink (text) {
var i=-1, v, r=[];
while (v=document.links[++i]) if ((''+v.innerHTML).match(text)) r.push(v);
return r;
}
It will turn an array of all <a> elements containing text. text can be a plain string or a regular expression.
Here's a version with an optional callback function. It will be called on all matching links. The first (and only) argument to the function is the <a> element. You can return false from your callback to stop finding links.
function findLink (text, callback) {
var i=-1, v, r=[], cb=callback||new Function;
while (v=document.links[++i]) if ((''+v.innerHTML).match(text)) {
r.push(v);
if (cb(v)===false) return r;
}
return r;
}
So, hiding the link according to the useragent sounds like a bad idea, but if you're dead set on it, you could do something like this (if I read your question right):
if ((''+navigator.userAgent).match(/BlackBerry|Android|iPhone/)) {
document.body.innerHTML+='<link rel="stylesheet" href="/m/css/mobile.css" type="text/css" />';
findLink('Find my Location', function (link) {
link.style.display='none';
return false;
});
}
Fairly simple, though not exactly efficient. This function will hide any anchor that has p_text inside it. Simply call hide('Find my Location') to accomplish what you want.
var hide = function(p_text, p_elem)
{
var elem = (p_elem) ? p_elem : document,
anchors = elem.getElementsByTagName('a'), i = 0;
for (i = 0; i < anchors.length; i++)
{
if (anchors[i].innerHTML.indexOf(p_text) >= 0)
{
anchors[i].style.display = 'none';
}
}
}
As for the user-agent, feature detection is the way to go, but if you're not browser-detecting to use different features, you may have to actually sniff the UA. Feature detection is great. It really is. When you're using the features you're detecting. But user-agent sniffing has its place, and this may be one of those cases.
[waits for the flame]
Edit: Added optional "p_elem" argument. If you have a container element, you can search that element only by calling hide('Find my Location', containerElement) where containerElement is a DOM node.
EDIT:
$("#mobileBtns > li:has(span:contains(TrainView))").hide();
Change TrainView to whatever text you want to search for. This selects the li element under mobileBtns that has a span that contains the text TrainView. If you want a non-jquery solution let me know.
function isBrowser(browserName)
{
var userAgent = navigator.userAgent;
for(var i = 0; i < browserName.length; i++)
{
if(userAgent.indexOf(browserName[i]) != -1)
{
return true;
}
}
return false;
}
if(isBrowser(["BlackBerry"]))
{
document.write('<link rel="stylesheet" href="/m/css/mobile.css" type="text/css" />');
}
else if(isBrowser(["iPhone", "Android", "Gecko", "MSIE", "Chrome", "Opera"]))
{
document.write('<link rel="stylesheet" href="/m/css/smartmobile.css" type="text/css" />');
}
else
{
document.write('<link rel="stylesheet" href="/m/css/mobile.css" type="text/css" />');
}
EDIT: You need to wrap the $(...) code after the document has loaded like this:
$(document).ready(function ()
{
$("#mobileBtns > li:has(span:contains(TrainView))").hide();
});
EDIT 2: Here's a javascript funciton that doesn't use jQuery to find/hide the list item. Replace the $(document).read()... with this code:
function hideListItem(text)
{
var ul = document.getElementById("mobileBtns");
for(var i = 0; i < ul.childNodes.length; i++)
{
var li = ul.childNodes[i];
// Element node.
if (li.nodeType == 1)
{
// Find the text in all of the inner-html.
if (li.innerHTML.indexOf(text) != -1)
{
li.style.display = "none";
break;
}
}
}
}
window.onload = function (e)
{
hideListItem("Schedules");
};
EDIT 3: Ok I think window.onload isn't supported in your version of the browser. What you can do is move the JavaScript call to hideListItem() code to the end of the body tag:
<html>
<head>
<!-- put your hideListItem function declaration here -->
</head>
<body>
<!--...stuff here...-->
<script type="text/javascript">
hideListItem("Schedules");
</script>
</body>
</html>
Why are you using user agents instead of just feature detection?
I presume you are looking for geolocation capabilities on the client, so why not simply check that:
function isGeolocationSupported() {
return !!navigator.geolocation;
}
See the GeoLocation API spec and a HTML5 site with more examples.
Also, I wouldn't add jQuery for this very feature as even 24K is a lot for mobile devices. You can use the Selectors API to query the text inside the span elements using:
var links = document.querySelectorAll("a.main");
for(var i = 0; i <links.length; i++) {
var link = links[i];
var span = link.querySelector('span');
var text = span.firstChild.nodeValue;
if(text == 'Find my Location') {
link.style.visibility = 'hidden';
}
}
Here's the same without the Selectors API.
var canQueryByClass = 'getElementsByClassName' in document;
var canQueryByTag = 'getElementsByTagName' in document;
if(!(canQueryByClass && canQueryByTag)) {
// hopeless client, no need to check further.
}
var links = document.getElementsByClassName("main");
for(var i = 0; i <links.length; i++) {
var link = links[i];
var span = link.getElementsByTagName('span');
if(span.length) {
var text = span.firstChild.nodeValue;
if(text == 'Find my Location') {
link.style.visibility = 'hidden';
}
}
}
See a working example.
​
Without assingning extra id you can make it like that:
var spans = document.getElementsByTagName('span');
for(i = 0; i < spans.length; i++)
if(spans[i].innerText == 'Find my location')
{
var aElement = spans[i];
while(aElement.tagName != 'a')
aElement = aElement.parentElement;
aElement.style.display = 'none';
}
This is pure JS solution, search for the span with the text, then follow up until finds the link element and hides it.
As for getting at the <a>, you can do this easily with jQuery:
$(".main").hide();
But you have another problem: You cannot access the user-agent from JavaScript. You will have to resort to a server-side script - and since your question mentions that you can't, you're out of luck for hiding the <a>.
Edit: give the <a> a unique ID, like:
<a id='user_agent_thing' ...
Then you can use:
$("#user_agent_thing").hide();
Further edit: you can find the specific element by its text this way:
var span_element = $('span').filter(function() { return $(this).text() == 'Find my Location'; });
Then you can hide the whole thing by doing:
span_element.parent().parent().parent().hide();
For the new HTML:
$('#mobileBtns li:contains(Find my Location)').hide();
For the old HTML:
This jQuery snippet should do the trick (test):
$('.main:has(.button_bg > span:contains(Find my Location))').hide();
To do what you probably want, which is guarded against i18n (test):
$('a.main[href$=media/findmy​​​​​​​​]').hide();
The last example shows that you can perform the hiding using CSS3:
a.main[href$=media/findmy] {
display: none;
}

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