Javascript - Link Name Changing with restrictions - javascript

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/

Related

How can i replace HTML tag to another in javascript

I am new with js and playing with replace method.
I have had no problems when replacing string for another string etc., but when im trying to do same with tags nothing happens..
Im trying to replace every tags for -tags. My function is below:
function bonus() {
var list = document.getElementsByTagName('li');
for (var i = 0; i < list.length; i++) {
newList = document.getElementsByTagName('li')[i].innerHTML;
newList = newList.replace('<li>', '<strong>');
newList = newList.replace('</li>', '</strong>');
document.getElementsByTagName('li')[i].innerHTML = (newList);
//console.log(newList);
}
}
function bonus(){
var list=document.getElementsByTagName('li');
var len = list.length;
for(var i=len-1; i>-1; i--){
var tmpItem = list[i]
newList = tmpItem.outerHTML;
newList = newList.replace('<li>','<strong>');
newList = newList.replace('</li>','</strong>');
tmpItem.outerHTML = newList;
}
}
I thought you might change your code like above, and there was still much space to optimize your code. go ahead <( ̄︶ ̄)>
First of all you should never replace a list-item with another element like that. A list item must always be a child of an ul or ol elelment, and ul and ol elements should not have any other immediate child that isn't a li.
However, this doesn't work because the li is an html element and not a text string and the inner HTML of an html elemnt doesn't contain the tag itself. It may contain children and those children's tags are part of the innerHTML, everything inside the element/tag itself is the innerHTML.
An example to clarify:
<ul>
<li>one<strong>second one</strong></li>
<li>two<strong>second two</strong></li>
<li>three<strong>second three</strong></li>
<li>four</li>
</ul>
Looping through all list items accessing elements as you've describe
for(var i=0; i<list.length;i++) {
console.log("==>> " + document.getElementsByTagName("li")[i].innerHTML);
}
Will output the following to the console:
==>> one<strong>second one</strong>
==>> two<strong>second two</strong>
==>> three<strong>second three</strong>
==>> four
If you want to make all li elements strong they should be nested as this:
<li><strong>Some text</strong></li>
To Achieve this one way to do it would be:
var list = document.getElementsByTagName("li");
for(var i=0; i<list.length; i++) {
var listItem = list[i];
listItem.innerHTML = "<strong>" + listItem.innerHTML + "</strong>";
}
If you want to convert all li elements to strong elements you must first remove them from the list...
Thanks alot for all of you. I knew that i can't change li for strong in real world, but i just tried to figure out if its possible to do so with simple loop.
My example html is full of lists, so thats why i used li instead of h2 to h3 or something like that. Outer html was new thing for me, and solution for this one. However Kim Annikas answer helped me with other question about modifying lists: I did this:
function replace(){
var list=document.getElementsByTagName('li');
for(var i=0;i<list.length;i++){
newText="<strong>Replaced!</strong>";
var listItem=list[i];
listItem.style.color="red";
listItem.innerHTML=newText;
}
}
..and now it seems that i have learnt how to modify tags as well as text inside of it ;)

How to find and change part of html in IE6 by javascript

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>

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.

JavaScript: get custom button's text value

I have a button that is defined as follows :
<button type="button" id="ext-gen26" class=" x-btn-text">button text here</button>
And I'm trying to grab it based on the text value. Hhowever, none of its attributes contain the text value. It's generated in a pretty custom way by the look of it.
Does anyone know of a way to find this value programmatically, besides just going through the HTML text? Other than attributes?
Forgot one other thing, the id for this button changes regularly and using jQuery to grab it results in breaking the page for some reason. If you need any background on why I need this, let me know.
This is the JavaScript I am trying to grab it with:
var all = document.getElementsByTagName('*');
for (var i=0, max=all.length; i < max; i++)
{
var elem = all[i];
if(elem.getAttribute("id") == 'ext-gen26'){
if(elem.attributes != null){
for (var x = 0; x < elem.attributes.length; x++) {
var attrib = elem.attributes[x];
alert(attrib.name + " = " + attrib.value);
}
}
}
};
It only comes back with the three attributes that are defined in the code.
innerHTML, text, and textContent - all come back as null.
You can do that through the textContent/innerText properties (browser-dependant). Here's an example that will work no matter which property the browser uses:
var elem = document.getElementById('ext-gen26');
var txt = elem.textContent || elem.innerText;
alert(txt);
http://jsfiddle.net/ThiefMaster/EcMRT/
You could also do it using jQuery:
alert($('#ext-gen26').text());
If you're trying to locate the button entirely by its text content, I'd grab a list of all buttons and loop through them to find this one:
function findButtonbyTextContent(text) {
var buttons = document.querySelectorAll('button');
for (var i=0, l=buttons.length; i<l; i++) {
if (buttons[i].firstChild.nodeValue == text)
return buttons[i];
}
}
Of course, if the content of this button changes even a little your code will need to be updated.
One liner for finding a button based on it's text.
const findButtonByText = text =>
[...document.querySelectorAll('button')]
.find(btn => btn.textContent.includes(text))

How to change the color of the links with javascript?

I want to know how can I manipulate all the links on a page with javascript. I can get elements by id's with document.getElementById(id), but how can I get the links? And also how can I get all elements with a certain classname? I want to change the color of the link and class elements.
I mean these links:
This is a link
And an example for an element with a class:
<span class="link">This is an element with a class</span>
Please no jquery. I want javascript.
Simple and straightforward (in pure JS too!)
colorLinks("#00FF00");
function colorLinks(hex)
{
var links = document.getElementsByTagName("a");
for(var i=0;i<links.length;i++)
{
if(links[i].href)
{
links[i].style.color = hex;
}
}
}
If it's a class name you're looking for and you know the tag, just use this.
var elements = document.getElementsByTagName("span");
for(var j=0;j<elements.length;j++)
{
if(elements[j].className === "your class here")
{
//do something
}
}
You can also look at getElementsByClassName and querySelectorAll. Both have support in most new browsers.
The pure-JavaScript version isn't all that complicated:
var elements = document.getElementsByTagName('a');
for (var i = 0; i < elements.length; i++) {
if (elements.className.split(/\s+/).indexOf('red') !== -1) {
elements[i].style.color = 'red';
}
}
And for modern browsers:
var elements = document.querySelectorAll('a.red');
[].slice.call(elements).forEach(function(elem) {
elem.style.color = 'red';
});
Update: I still recommend using jQuery, but, if you want to learn how to do it without, I would recommend heading over to this site. This shows how to change link colors when you mouse over the link, but you can easily extrapolate for your specific situation: Javascript Change Link Text Color onmouseover
--
Ottomanlast has a good point about checking out jQuery to help you out with this task (although it can be done without the use of a library). However, just so you have an example of what he is talking about, here is how you could change link colors using jQuery.
$('.linkClass').click(function(){
$(this).css('color', 'green');
});
This example changes the color of a specific link when it is clicked.
$('a').css('color', 'green');
This example will change all the links to a green color.
$('.linkClass').click(function(){
$(this).removeClass('oldClass');
$(this).addClass('newClass');
});
This does the same thing as the first example, but this removes and adds CSS classes that you already have defined elsewhere. (I would recommend this method over just editing the CSS directly.)
Anyway, the point I'm trying to make is that jQuery makes it extremely easy to select and then make changes to the objects within your HTML document. You may want to take a look into it.
You can use document.getElementsByTagName("a"). This function returns an array of the <a> elements in the page. Loop over this array, and use .style.color = "#000000" in each element.
This is how I change all hyperlink colors (normal/hover):
function changeTextHyperlinkColours(inputColorNormal, inputColorHover) {
var sheets = document.styleSheets;
var slen = sheets.length;
for(var i=0; i<slen; i++) {
var rules = document.styleSheets[i].cssRules;
var rlen = rules.length;
for(var j=0; j<rlen; j++) {
if (rules[j].selectorText == 'a') {
rules[j].style['color'] = inputColorNormal;
}
if (rules[j].selectorText == 'a:hover') {
rules[j].style['color'] = inputColorHover;}
}
}
}
}
Also you can embed the link text in the span and change the color
<a href='www.mydomain.com'><span onclick='this.style.color="red"'>Visit Us</span></a>

Categories