Greasemonkey script to replace href - javascript

My html looks like this
<a class="jx_ui_html_a" target="_blank" __jx__id="___$_2854__a" href="https://www.kitty.com">
<div class="jx_ui_html_div path_title" __jx__id="___$_2854__path"></div>
</a>
and
i am trying to find a greasemonkey script which changes the href part from ANYTHING to https://www.dog.com if the A class is jx_ui_html_a
so the result should be
<a class="jx_ui_html_a" target="_blank" __jx__id="___$_2854__a" href="https://www.dog.com">
<div class="jx_ui_html_div path_title" __jx__id="___$_2854__path"></div>
</a>
respectively
<a class="jx_ui_html_a" target="_blank" __jx__id="___$_28254__a" href="https://www.dog.com">
<div class="jx_ui_html_div path_title" __jx__id="___$_28254__path"></div>
</a>
Could you please help me in any way?

The following is two lines of code - the first one queries the DOM to find all a tags (document.querySelector('a') and converts it into an array (by passing it as an argument to [].slice.call), and the second runs a forEach function on the array, which reassigns the href attribute of every DOM Element in the array.
var anchors = [].slice.call(document.querySelectorAll('a');
anchors.forEach(function(element){
element.href = "http://www.dog.com/"
});
Same thing without forEach:
var anchors = document.querySelectorAll('a');
for(var i=0;i<anchors.length;i++){
anchors[i].href = "http://www.dog.com";
}
To limit the elements of anchors to only those with specific class name, supply it as part of the querySelector argument:
var anchors = document.querySelectorAll('a.jx_ui_html_a')
querySelector and querySelectorAll select elements the same way that rendering engines which apply CSS rules do. So you can pass it things like "p > a" (will return 'a' elements that are direct descendants of 'p' elements), and "div#container span" (which will return span elements that are anywhere inside the div with 'container' id).
querySelector returns the first match, while querySelectorAll returns an array-like list of all matching elements.

First you'll want to require jQuery. You can read about how to do that here.. Once that's installed you can run something like the following:
$(document).ready(function() {
$('.jx_ui_html_a').attr('href','http://www.dog.com');
});
In English, that will wait until the page is fully loaded ($(document).ready()), search for all elements with your specified class ($('.jx_ui_html_a')), and replace all of their href attributes with your specified URL.

Related

How add ID to HTML href with javascript

I have an HTML like this
<div class="this">
EXP
</div>
I want to add id to <a>. But do not know what to do.
First select your element using something like .getElementsByClassName(). Keep in mind that .getElementsByClassName() returns a NodeList collection of elements, so you'll want to access the first index (or loop over them). You can then simply set the ID with .id, as the ID is merely a property of an element.
This can be seen in the following:
const element = document.getElementsByClassName('this')[0];
element.id = 'element';
console.log(element);
<div class="this">
EXP
</div>
If you want to add this with Javascript, you'll need to use a selector to target your <a> tag and then set the id attribute on it. You can do this by using the querySelector() function or as seen below:
// Find an <a> tag that occurs below a class called "this" and set its id attribute
document.querySelector('.this > a').id = "some-id";
There are many other available functions to handle this through native Javascript and other frameworks, so your milage may vary depending on what you are using.
Example
In this example, we have provided some CSS that should only apply to an element with an id of "test" and we'll run the necessary code to show that the id is being added to the element (as it will be red):
document.querySelector('.this > a').id = 'test';
#test { color: red; }
<div class="this">
EXP
</div>
Add the id attribute to the <a> tag. See the differences of the middle line:
<div class="this">
<a id="expid" href="exp.com">EXP</a>
</div>

Append new path in all the a href URL

I have seen the post How to update (append to) an href in jquery? , but it doesn't seem like the answer can help at my case.
I am currently using a plugin(easytab) to create a few different tab and every tab contains a tag like <a id="tabopen" href="www.text.com/custom/questions/ask/">
<a id="tabopen" href="www.text.com/default/questions/ask/">
and for some reason I have a button which append some extra path to all the href in order to redirect user to the right place.
I have tried to use
$("a#tab1").each(function() {
var _href = $(this).attr("href");
$(this).attr("href", _href + 'startDate=20160121?endDate=20160212');
});
but instead append the 'startDate=20160121?endDate=20160212' it replace everything to www.text.com/custom/questions/ask/startDate=20160121?endDate=20160212 , which is not right, how should i fix it?
Update 1:
I am sorry that i have provide wrong description at, the ids are actually the same in the plugin.
<a id="tabopen" href="www.text.com/custom/questions/ask/">
<a id="tabopen" href="www.text.com/default/questions/ask/">
$("a#tab1") selects a single <a> element having ID as tab1. To change the href attribute of a single element there is no need of each.
var href = $('a#tab1').attr('href') + '?startDate=20160121&endDate=20160212';
$('a#tab1').attr('href', href);
If having multiple elements with same ID, ID should be unique.
To select all the elements whose ID starts with tab, you can use attribute start with selector. I'll suggest to use a unique class on them.
To change the href attribute value of all the matched elements .attr(attributeName, function) with callback function can be used.
$('a[id^="tab"]').attr('href', function(i, oldHref) {
return oldHref + '?startDate=20160121&endDate=20160212';
});
As said by #charlietfl in the comment, the querystring format should be as follow
'?startDate=20160121&endDate=20160212'
^ ^
Update:
Saying again, ID should be unique., you can use class instead of ID for similar purpose elements.
Change the markup to use class
<a class="tabopen" href="www.text.com/custom/questions/ask/">
<a class="tabopen" href="www.text.com/default/questions/ask/">
And then use the selector
$('.tabopen').something...
BAD PRACTICE:
If you can't change the markup(auto-generated markup by some plugin), you can use attribute value selector to select all elements having same ID
$('a[id="tabopen"]').something...

How to replace all id from href?

I have the following markup
<div class = "general">
<div id ="custom"></div>
</div>
How to change id = "custom" in all <div> with class="general" from href on page using jQuery?
You can try this:
$("div.general").each(function() {
$(this).children("div#custom").text($(this).children("a").attr("href"));
});
If I understand you correctly, you want to iterate through all div.generals, and change the text of each child div#custom to the href of the child a.
See a working example on JSfiddle.
Also, another tip is to avoid using multiple elements with the same id. In your code you have a <div> with id="custom". You also say that the div.general appears multiple times — therefore, the id "custom" will appear multiple times. This is bad practice. I suggest that you change id to class.
You need to loop through all div.general and replace the id attribute of div#custom to whatever is there as the anchors href property. The following code will work:
$(".general").each(function(){
$(this).find("#custom").attr("id", $(this).find("a").attr("href").replace("#", ""));
})
Here the .find() will dig out elements from any depth inside the parent. If you are sure about the DOM position of the elements, you can change the .find() to .children()

Is Id necessary in applying jquery functions?

Suppose I have two p tags in the document. I want to call two different effects using jQuery when onMouseOver event happens. Is it necessary that these two p tags be given Ids. Can't it be achieved without giving Ids to these tags ?
You don't have to give anything an id, however it is the best way to uniquely identify an element.
You can instead idenfity by class:
$(".myClass")
By attribute:
$("[src='image.jpg']")
By position in parent:
$("p:eq(2)")
A full list of selectors is available in the documentation
$('p:first'); // first p tag
$('p:last'); // last p tag
$('p').eq(1); // exactly the second p tag
There are several ways to select an element / elements:
$('.classname')
$('#id')
$('tagname')
$('[attr="value"]')
etc
although jQuery allows you to write faster and easier scripts, but unfortunately it makes you never understand the real JavaScript.
$("*") //selects all elements.
$(":animated") //selects all elements that are currently animated.
$(":button") //selects all button elements and input elements with type="button".
$(":odd") //selects even elements.
$(":odd") //selects odd elements.$("p") selects all <p> elements.
$("p.intro") //selects all <p> elements with class="intro".
$("p#intro") //selects the first <p> elements with id="intro".
$(this) //Current HTML element
$("p#intro:first") //The first <p> element with id="intro"
$("p:eq(2)") // The third <p> element in the DOM
$(".intro") //All elements with class="intro"
$("#intro") //The first element with id="intro"
$("ul li:first") //The first <li> element of the first <ul>
$("ul li:first-child") //The first <li> element of every <ul>
$("[href]") //All elements with an href attribute
$("[href$='.jpg']") //All elements with an href attribute that ends with ".jpg"
$("[href='#']") //All elements with an href value equal to "#"
$("[href!='#']") //All elements with an href value NOT equal to "#"
$("div#intro .head") //All elements with class="head" inside a <div> element with id="intro"
jQuery – Select element cheat sheet

How can I get img src and text from distant elements using JQuery?

Could you please lend a hand as I am having some trouble getting the text of a heading and the source of an image element in order to create a list of the item clicked. But I will explain better with some code:
Firstly I have a div element that goes like this:
<div class="main_page_entry">
<div class="main_item_desc">
<img class="main_item_pic" src="blah.jpg" />
<h6>Item Title</h6>
<span class="icon"> <img src="icon.png" /></span><br />
<span class="address">Some address</span>
<p class="item_desc">More blahs and links for description </p>
</div>
<div class="item_controls">
...
<a href="#" class="add_to_list">
<img src="add_icon.gif" />Add to List
</a>
...
</div>
</div>
It consists with a big div containing two smaller. What I want to do is the following: When I click on 'Add to List' link, I would like to get just the text inside and the main_item_pic source in order to create a list item with those two.
So here is my written code so far:
$('a.add_to_list').live('click', function() {
var name = $(this).closest('h6').text();
var source = $(this).closest('.main_item_pic').src;
$('<li class="hide list_entry"><span class="entry_title">'+
name+'</span><button class="remove_entry"></button>'+
'<img class="list_entry" src="'+source+'" /></li>')
.appendTo('#favs_list ul')
.show('slow');
});
Obviously this doesn't work! I've tried different solutions that I read around here like:
var name = $(this).closest('h6').html();
var source = $(this).closest('.main_item_pic').attr('src');
but oh well...no luck so far. Any ideas? Thanks in advance!
Try going back to the top and coming down again along the right DOM branch:
var src = $(this).closest('.main_page_entry') // Back to the top
.find('.main_item_desc .main_item_pic') // And down again.
.attr('src');
The closest method goes up the DOM tree through your ancestors:
Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.
So it won't cross over to any of the sibling branches. Then, once you're at the appropriate ancestor, you use find to come back down, find is just like $() but uses the specified element rather than document as the root:
Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
The closest method only finds the closest ancestor that matches the selector you pass it. Because the h6 and img you are looking for are not ancestors of the element you are calling it on, it won't find them. What you need is to find the closest element that contains both the element you are searching from and the elements you are trying to find, and use it as an intermediate step in the search:
var name = $(this).closest('.main_page_entry').find('h6').text();
var source = $(this).closest('.main_page_entry').find('.main_item_pic').attr('src');
First off, if this content isn't added dynamically or in a live manner (in other words, if the content is loaded with the original HTML load) then you do not have to use the .live() function.
Also, why are you using .closest()? Couldn't you just do:
<img class="main_item_pic" ref='pic1' src="blah.jpg" />
<a ref='pic1' href="#" class="add_to_list">
<img src="add_icon.gif" />Add to List
</a>
$('a.add_to_list').click(function(){
var ref = $(this).attr('ref');
var src = $("img[ref='" + ref + "']").attr('src');
var name = $('h6 a').text();
});
The method closest() looks for ancestors. Your h6 and img are not ancestors of your link.
Also, I guess you don't want $('h6').html() but $('h6 a').html()

Categories