I am curious if pure javascript can replace this jQuery selector for IE7 and greater..
Do people simply change the markup and select using a class or is their away of selecting this using pure javascript
<h1 rel="xxxexternalxxx">Attribute Contains</h1>
var arrinput = $('[rel*="external"])
Any help would be much appreciated, thank you in advance
You can use getElementsByAttribute, then loop and filter:
var rels = getElementsByAttribute('rel');
var attr = 'external';
var result = [];
for (var i=0; i<rels.length; i++) {
if (rels[i].getAttribute('rel').indexOf(attr) > -1) {
result.push(rels[i]);
}
}
Related
I have webpage and I need to make some changes in this page. I am using IE6 in compatibility mode:
The part of html I need to change seems like this:
<SPAN title="Klepnutím otevřete"
class=attachment url="/Activities/Attachment/download.aspx"
userId="{4618A8F6-8B8F-E611-940B-005056834715}"
merchantId="{74F4AC81-FB14-DC11-BF2E-00145ED73B3E}"
attachmentType="5"
attachmentId="{1828327C-74A6-E611-940B-005056834715}">
<IMG border=0
src="/_forms/attachments/16_generic.gif"
align=absMiddle> Account.xml
</SPAN>
I would like to change the url to something else by javascript.
Is there some way how to do it? I know, that there are some fuctions like getelementbyId, but I can not use it, as this element does not have the ID. Also it seems, that I can not use xpath, as it is not supported in IE6.
Thanks for all replies!
You said you're getting this: Object doesn't support property or method 'getElementsByClassName'
That means the document doesn't have that method on it. Here's a good polyfill for that method in older IEs:
function getElementsByClassName(node, classname) {
var a = [];
var re = new RegExp('(^| )'+classname+'( |$)');
var els = node.getElementsByTagName("*");
for(var i=0,j=els.length; i<j; i++)
if(re.test(els[i].className))a.push(els[i]);
return a;
}
Once that function is declared, you can use it. Just remember that it's not a method on the document like it would be in older browsers.
var spans = var tabs = getElementsByClassName(document.body,'span');
for(var i = 0; i < spans.length; i++) {
var title = spans[i].getAttribute('title');
if(title === "Klepnutím otevřete") {
spans[i].setAttribute('url', 'this/is/your/custom/url.aspx')
}
}
Here, I used the title attribute to try and find the right span. I have no idea if this title is unique to just this span element, so you might need to validate that and select it differently if needed.
Simply use getElementsByTagName
var spans = document.getElementsByTagName('span');
for (var i = 0; i < spans.length; i++) {
// find an element with a certain class
if (spans[i].getAttribute('class') == 'attachment') {
// set new value
spans[i].setAttribute('url', 'some other url');
}
}
<SPAN title="Klepnutím otevřete"
class="attachment"
url="/Activities/Attachment/download.aspx"
userId="{4618A8F6-8B8F-E611-940B-005056834715}"
merchantId="{74F4AC81-FB14-DC11-BF2E-00145ED73B3E}"
attachmentType="5"
attachmentId="{1828327C-74A6-E611-940B-005056834715}">
<IMG border=0
src="/_forms/attachments/16_generic.gif"
align="absMiddle"/> Account.xml
</SPAN>
From the given HTML, I am trying to extract the pText array, so that I end up with two <p> items (in this case), from which I can extract the two text strings "link test1" and "link test2", and pop an alert for each of them. Why doesn't the below script work?
HTML:
<div>
<p><a href='/'>link</a> test1</p>
<p><a href='/'>link</a> test2</p>
</div>
Javascript:
var pText = $('div').find('p');
for (i = 0; i < pText.length; i++) {
alert(pText[i].text());
}
Since that you're using jQuery, if you want to use the .text() method you have to extract a jQuery object and use .eq(i) instead of [i], which returns a normal element.
Here's the correct code:
var pText = $('div').find('p');
for (i = 0; i < pText.length; i++) {
alert(pText.eq(i).text());
}
Also, you can simplify your code using the .each() method (instead of the for loop), which calls a given function for every element of your jQuery collection (pText). In my opinion, it's easier, here you go:
var pText = $('div').find('p');
pText.each(function(i, el) {
alert($(el).text());
});
text() is a function for jQuery objects.
Use it by wrapping your element in $(..)
alert($(pText[i]).text());
And a better way is to use .each()
$('div').find('p').each(function(){
alert($(this).text());
});
Try using alert(pText.eq(i).text()); instead of alert(pText[i].text());
The jQuery code will be
var pText = $('div').find('p');
for (i = 0; i < pText.length; i++) {
alert(pText.eq(i).text());
}
$('#x').children('p').each(function() {
alert($(this).text()); // "this" is the current element in the loop
});
JSFiddle
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.
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/
A while ago I was making some test in JavaScript,
and played with a code to get the text of all elements with a certain class.
Now I was trying to make something like this but obtain all elements by a certain type, for example all elements type="text"
Is there any way to do this in JavaScript or should I use jQuery?
var xx = document.getElementsByClassName("class");
for (i=0;i<xx.length;i++){
var str=xx[i].innerHTML;
alert(str);
}
If you are lucky and need to care only for recent browsers, you can use:
document.querySelectorAll('input[type=text]')
"recent" means not IE6 and IE7
In plain-old JavaScript you can do this:
var inputs = document.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
if(inputs[i].type.toLowerCase() == 'text') {
alert(inputs[i].value);
}
}
In jQuery, you would just do:
// select all inputs of type 'text' on the page
$("input:text")
// hide all text inputs which are descendants of div class="foo"
$("div.foo input:text").hide();
The sizzle selector engine (what powers JQuery) is perfectly geared up for this:
var elements = $('input[type=text]');
Or
var elements = $('input:text');
var inputs = document.querySelectorAll("input[type=text]") ||
(function() {
var ret=[], elems = document.getElementsByTagName('input'), i=0,l=elems.length;
for (;i<l;i++) {
if (elems[i].type.toLowerCase() === "text") {
ret.push(elems[i]);
}
}
return ret;
}());