Replace All URLs within DIV - javascript

I would like to amend all URLs within a specified DIV but unsure how to. An example I want is:
<div id="SearchList">
up
down
left
right
</div>
So for example I would like to amend the URLs to be displayed as follows:
<div id="SearchList">
up
down
left
right
</div>
Any ideas how this can be achieved?

// For each anchor element...
$("#SearchList a").each(function() {
// Change its 'href' attribute to...
$(this).attr("href",
// Its current 'href' attribute with a .replace() called
$(this).attr("href").replace("google", "bing"));
});

This is what I would do
$('#SearchList a').each(function(){
var $el = $(this),
hash = $el.attr('href'),
replace = 'www.bing.com',
regex = /www.+.com\//,
replacement = hash.replace(regex, replace);
$el.attr('href', replacement);
});

Shorter would be
$('a').prop('href', function(i,e){ return e.replace('google', 'bing')});

Related

Finding a span where the class contains a text string JQuery

I am using JQuery to find a span element that contains a string of text in the class, but could also contain other text.
var not_breaks = element.filter("span.this_text");
This works for spans where class="this_text" but not class="this_text_and_more_text" - I need to search for both.
In that case you could use the Attribute Contains selector:
var not_breaks = element.filter("span[class*='this_text']");
You could also use the Attribute Starts With selector, but note that this is only guaranteed to work if the element has a single class on it:
var not_breaks = element.filter("span[class^='this_text']");
We can get all the span class with the name by using a hasclass, Will this help you
var pare=$('span');
$( pare ).each(function() {
if($(this).hasClass('httext')){
alert($(this).html())
}
});
I need to search for both
I'd do that with a selector group:
var not_breaks = element.filter("span.this_text, span.this_text_and_more_text");
// first ---^ comma ---^ ^---- second
That will retain elements matching either selector in the group.
Example:
var element = $("span");
var not_breaks = element.filter("span.this_text, span.this_text_and_more_text");
not_breaks.css("color", "green");
<div><span>Not a match</span></div>
<div><span class="this_text">this_text</span></div>
<div><span>Not a match</span></div>
<div><span class="this_text_and_more_text">this_text_and_more_text</span></div>
<div><span>Not a match</span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use regex to retrieve the any sequence as you need.
var regex = new RegExp("this_txt");
var elem = $("span").filter(function () {
return regex.test($(this).attr('class'));
});
console.log(elem.length);
regex.test function will only return true if the sequence exists.
here's the fiddle
https://jsfiddle.net/yt1cr2zb/

js How to add href + text onclick

I need to pass (using javascript) text inside span to href
<div class='tableCell'><span>information</span></div>
<div class='tableCell'><span>contact</span></div>
<div class='tableCell'><span>about</span></div>
for example when i click to about link must be example.com/tag/about/
Here is my Answer. I'm using Javascript to manipulate the DOM to add a new element with the href equal to the inner text within the span element.
I hope you find this answer helpful.
Thanks.
var spans = document.getElementsByTagName('span')
var baseUrl = 'http://example.com/tag/'
for(var i=0; i<spans.length; i++)
{
var curElement = spans[i];
var parent = curElement.parentElement;
var newAElement = document.createElement('a');
var path = baseUrl+curElement.innerHTML;
newAElement.setAttribute('href', path);
newAElement.appendChild(curElement);
parent.appendChild(newAElement)
}
DEMO
The simplest way:
$( "span" ).click(function() {
var link = 'http://yousite.com/tag/'+ $(this).text().replace(/ /, "-")+"/";
window.location.href= link.toLowerCase();
});
DEMO
http://codepen.io/tuga/pen/yNyYPM
$(".tableCell span").click(function() {
var link = $(this).text(), // will provide "about"
href = "http://example.com/tag/"+link; // append to source url
window.location.href=href; // navigate to the page
});
You can try the above code
You do not have links but span in your html. However, you can get build the href you want and assign it to an existing link:
$('div.tableCell').click(function(){
var href = 'example.com/tag/' + $(this).find('span').text();
})
Lets work with pure javascript, I know you want to use jQuery but I am really sure too many people can't do this without looking in to web with pure javascript. So here is a good way.
You can follow it from jsFiddle
var objectList = document.getElementsByClassName("tableCell");
for(var x = 0; x < objectList.length; x++){
objectList[x].addEventListener('click', function(){
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML;
});
}
Lets work on the code,
var objectList = document.getElementsByClassName("tableCell");
now we have all element with the class tableCell. This is better than $(".tableCell") in too many cases.
Now objectList[x].addEventListener('click', function(){}); using this method we added events to each object.
top.location.href = "example.com/tag/" + this.childNodes[0].innerHTML; with this line if somebody clicks to our element with class: We will change the link to his first child node's text.
I hope it is useful, try to work with pure js if you want to improve your self.
Your Method
If you always are going to have the url start with something you can do something like this. The way it is set up is...
prefix + THE SPANS TEXT + suffix
spaces in THE SPANS TEXT will be converted to -
var prefix = 'http://example.com/tag/',
suffix = '/';
$('span').click(function () {
window.location.href = prefix + $(this).text().replace(' ', '-').trim().toLowerCase() + suffix;
//An example is: "http://example.com/tag/about-us/"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='tableCell'><span>Information</span></div>
<div class='tableCell'><span>Contact</span></div>
<div class='tableCell'><span>About</span></div>
You can adjust this easily so if you want it to end in .html instead of /, you can change the suffix. This method will also allow you to make the spans have capitalized words and spaces.
JSBIN

jQuery select href values in nested divds

Although I found several answers to select a href attribute neither of them is working for me. Maybe someone can help.
The html is as follows
<div class="galleryitem">
<div class="itemlink">
Page
</div>
<div class="itemimg">
test1.png
</div>
</div>
<div class="galleryitem">
<div class="itemlink">
Page 1
</div>
<div class="itemimg">
test2.png
</div>
</div>
Now i want to geht all the attribute values in the hrefs and tried with
$('.galleryitem').each(function() {
var link = $(this).children('itemlink a').attr('href');
var img = $(this).children(".itemimg a").attr("href");
//jQuery("#somediv").append("<a href='" + link + "'><img class='cloudcarousel' src='" + img + "'/></a>");
});
I dont know why link and img are undefined. Even $(this).children('.itemlink a') is undefined.
Can anyone help on this?
Try with find
$('.galleryitem').each(function() {
var link = $(this).find('itemlink a').attr('href');
var img = $(this).find(".itemimg a").attr("href");
//...
})
you want to sure the .find() method instead of .children which only grabs the immediate descendants. (you also have a small error missing the period in itemlink)
var link = $(this).find('.itemlink a').attr('href');
var img = $(this).find(".itemimg a").attr("href");
should work for you, and here is a fiddle: http://jsfiddle.net/hQeu3/
the reason .children doesn't works is that there are no immediate descendents that match this selector '.itemlink a'. jQuery grabs the divs (".itemlink"), and then tries to filter to the selector, which fails in this case. it is essentially equal to
$(this).children().filter('.itemlink a'); //won't work!
if you want to use children you could do
$(this).children('.itemlink').children("a").attr('href');
You could do as follows:
$('.galleryitem').each(function() {
var link = $('.itemlink > a', this).attr('href');
var img = $('.itemimg > a', this).attr('href');
});
which take into account that .itemlink and .itemimg are a direct parent of the <a> element.

JQuery replace html element contents if ID begins with prefix

I am looking to move or copy the contents of an HTML element. This has been asked before and I can get innerHTML() or Jquery's html() method to work, but I am trying to automate it.
If an element's ID begins with 'rep_', replace the contents of the element after the underscore.
So,
<div id="rep_target">
Hello World.
</div>
would replace:
<div id="target">
Hrm it doesn't seem to work..
</div>​
I've tried:
$(document).ready(function() {
$('[id^="rep_"]').html(function() {
$(this).replaceAll($(this).replace('rep_', ''));
});
});​
-and-
$(document).ready(function() {
$('[id^="rep_"]').each(function() {
$(this).replace('rep_', '').html($(this));
});
​});​
Neither seem to work, however, this does work, only manual:
var target = document.getElementById('rep_target').innerHTML;
document.getElementById('target').innerHTML = target;
Related, but this is only text.
JQuery replace all text for element containing string in id
You have two basic options for the first part: replace with an HTML string, or replace with actual elements.
Option #1: HTML
$('#target').html($('#rep_target').html());
Option #2: Elements
$('#target').empty().append($('#rep_target').children());
If you have no preference, the latter option is better, as the browser won't have to re-construct all the DOM bits (whenever the browser turns HTML in to elements, it takes work and thus affects performance; option #2 avoids that work by not making the browser create any new elements).
That should cover replacing the insides. You also want to change the ID of the element, and that has only one way (that I know)
var $this = $(this)
$this.attr($this.attr('id').replace('rep_', ''));
So, putting it all together, something like:
$('[id^="rep_"]').each(function() {
var $this = $(this)
// Get the ID without the "rep_" part
var nonRepId = $this.attr('id').replace('rep_', '');
// Clear the nonRep element, then add all of the rep element's children to it
$('#' + nonRepId).empty().append($this.children());
// Alternatively you could also do:
// $('#' + nonRepId).html($this.html());
// Change the ID
$this.attr(nonRepId);
// If you're done with with the repId element, you may want to delete it:
// $this.remove();
});
should do the trick. Hope that helps.
Get the id using the attr method, remove the prefix, create a selector from it, get the HTML code from the element, and return it from the function:
$('[id^="rep_"]').html(function() {
var id = $(this).attr('id');
id = id.replace('rep_', '');
var selector = '#' + id;
return $(selector).html();
});
Or simply:
$('[id^="rep_"]').html(function() {
return $('#' + $(this).attr('id').replace('rep_', '')).html();
});
From my question, my understanding is that you want to replace the id by removing the re-_ prefix and then change the content of that div. This script will do that.
$(document).ready(function() {
var items= $('[id^="rep_"]');
$.each(items,function(){
var item=$(this);
var currentid=item.attr("id");
var newId= currentid.substring(4,currentid.length);
item.attr("id",newId).html("This does not work");
alert("newid : "+newId);
});
});
Working Sample : http://jsfiddle.net/eh3RL/13/

navigating the dom javascript specific tag

Here it is DOM structure:
<div id="some">
NOTHIS
NOTHIS
<h3 class="myclass">HELLO</h3>
</div>
How can I get the value of HELLO in javascript?
EDIT: Forgot, I have other anchor tags inside 'some', so I want strictly the anchor tag inside the h3's
EDIT2: Got it:
var n = document.getElementById('some').getElementsByTagName('h3')[0].getElementsByTagName('a')[0].innerHTML;
Thanks all!
var linkText = document.getElementById('some').getElementsByTagName('a')[0].innerHTML;
or if you have jQuery
var linkText = $('#some').find('a').html();
var anchor = document.getElementById('some').getElementsByTagName('a')[0],
yourText = anchor.innerText || anchor.textContent;
It's cross-browser, too. http://www.quirksmode.org/dom/w3c_html.html
Propagate down the DOM from your ID.
var s = document.getElementById('some').getElementsByTagName('h3')[0].getElementsByTagName('a')[0].innerHTML;
I would put an ID on the a myself.
var shouldEqualHello = document.getElementById('some').getElementsByTagName('h3')[0].getElementsByTagName('a')[0].innerHTML;
edit: fixed
to get to a single dom element with javascript, you need a way to uniquely identify it. the ideal approach is to give your element a unique id.
<a id="myAnchor" href="#" style="color:red;">HELLO</a>
then you can directly obtain a reference in script.
var myAnchor = document.getElementById('myAnchor');
or if you are guaranteed that your element is the only anchor element within the "some" id you can do
var someDiv = document.getElementById('some');
var anchors = someDiv.getElementsByTagName('a'); // returns a list of anchor elements
var myAnchor = anchors[0]; // get the first element in the list
but since that's not the case you'll have to pick your way down through the dom some more.
var someDiv = document.getElementById('some');
var headers = someDiv.getElementsByTagName('h3');
var myH3 = headers[0];
var anchors = myH3 .getElementsByTagName('a'); // returns a list of anchor elements
var myAnchor = anchors[0]; // get the first element in the list
from there you can see the stuff between the tags with
alert(myAnchor.innerHTML);
or
alert(myAnchor.firstChild.nodeValue);
or some other method already mentioned here.
You could simply use query selector,
let result = document.querySelector('#some h3 a').innerText;
console.log(result);

Categories

Resources