Creating links for elements with a particular class with jQuery - javascript

How can I wrap every element belonging to a particular class with a link that is built from the text inside the div? What I mean is that I would like to turn:
<foo class="my-class>sometext</foo>
into
<a href="path/sometext" ><foo class="my-class>sometext</foo></a>
Url encoding characters would also be nice, but can be ignored for now if necessary.
EDIT: Just to clarify, the path depends on the text within the element

Use jQuery.wrap() for the simple case:
$(".my-class").wrap("<a href='path/sometext'></a>");
To process text inside:
$(".my-class").each(function() {
var txt = $(this).text();
var link = $("<a></a>").attr("href", "path/" + txt);
$(this).wrap(link[0]);
});

$(".my-class").each(function(){
var thisText = $(this).text();
$(this).wrap("<a></a>").attr("href","path/"+thisText);
});

you can wrap them inside anchor element like this:
$(document).ready(function(){
$(".my-class").each(function(){
var hr="path/"+$(this).text();
$(this).wrap("<a href='"+hr+"'></a>");
});
});
if you are opening links in same page itself then easier way than modifying dom to wrap elements inside anchor is to define css for the elements so that they look like links then handle click event:
$(".my-class").click(function(){
window.location.href="path/"+$(this).text();
});

$("foo.my-class").each(function(){
var foo = $(this);
foo.wrap("<a href='path/" + foo.Text() +"'>");
});

This ought to do it:
$('foo.my-class').each(function() {
var element = $(this);
var text = element.html(); // or .text() or .val()
element.wrap('');
});

Related

Using Javascript to hide text shown on currency switch

I'd like to use Javascript (on page load) to remove the wording 'Choose a currency to display the price:'.
Leaving just the currency icons in the box (Div id = currency-switch).
How can I do this?
Page url: http://www.workbooks.com/pricing-page
Image example:
You can remove this text with for example:
window.onload = function(){
var el = document.getElementById("currency-switch");
var child = el.childNodes[0];
el.removeChild(child);
};
If you want to keep it stupid simple just add an span around the text and give it an id like "currency_text".
Then you only need this code:
var elem = document.getElementByid("currency_text");
elem.remove();
Try
$(document).ready(function() {
var currencyDiv = $('#currency-switch');
currencyDiv.innerHTML(currencyDiv.innerHTML().replace("Choose a currency to display the price:", ""));
}
This will remove the text as soon as the DOM is ready.
Please see below which will just remove the text:
This will trigger on page load
<script>
// self executing function here
(function() {
var selected_div = document.getElementById('currency-switch');
var text_to_change = selected_div.childNodes[0];
text_to_change.nodeValue = '';
})();
</script>
Since it's a text node, you could do the following in jQuery. This will be triggered on DOM ready.
$(function() {
jQuery("#currency-switch").contents()
.filter(function() {
return this.nodeType === 3;
}).remove();
});
You can use this code:
var requiredContent = document.getElementById('currency-switch').innerHTML.split(':')[1];
document.getElementById('currency-switch').innerHTML = requiredContent;
See it working here: https://jsfiddle.net/eg4hpg4z/
However, it is not very clean, but should work, if you cant directly modify the html.
A better solution would be to modify your code to move the text content within a span and show hide the text like so:
HTML:
<div id="currency-switch">
<span class="currency-label">Choose a currency to display the price: </span>
<span class="gb-background"><span class="GB"> £ </span></span><span class="es-background"><span class="ES"> € </span></span><span class="au-background"><span class="AU"> $ </span></span></div>
Javascript:
document.getElementsByClassName('currency-label')[0].style.display = 'none';

Create "title" attribute using the text inside <a> tag?

Is it possible to take the text inside of an <a> tag and add it to title attribute of that tag using JavaScript?
For example:
Hello
I want the text "hello" to be the title attribute to the <a> tag. Like this:
Hello
Can this be done with JavaScript? Any help or direction would be appreciated.
In javascript, as requested:
var anchors = document.getElementsByTagName('a');
for(i = 0;i < anchors.length; i++) {
anchors[i].title = anchors[i].textContent;
}
http://jsfiddle.net/spencerooni/z97rc/
If you have an ID for the specific tag (e.g. ...):
$('#atag').attr('title', $('#atag').text());
or if you'd like to do this for all a tags:
$('a').each(
function() {
$(this).attr('title', $(this).text());
}
);
DEMO
$('a').each(function() {
var $this = $(this); /* slight optimisation over using $(this) twice */
$this.attr('title',$this.text());
});
In the most simple jQuery form:
$('a').attr('title', function(){ return $(this).text() })
jsFiddle example

jQuery hide inner html, except for a tags

I have the following HTML:
<div class="content-body attribute-pdf">
<a href="/_fragment/content/download/296/1935/file/blabla.pdf">
blabla.pdf</a> 1.2 Mb
</div>
This is coming out of a CMS, and I would like to hide this "1.2 MB",but still keep the A href part
is this possible to do in jQuery ?
I tried this:
$(".attribute-pdf").children().hide();
which hides the A href, but still shows the text. I want it vice-versa - hide the text, but still show the A href.
A quick way, in jQuery - empty the div, replace its contents with just the <a> tag:
$('.attribute-pdf').each(
function() {
var container = $(this);
var a = container.find('a').detach();
container.empty().append(a);
}
);
Example: http://codepen.io/paulroub/pen/iaFnK
You could set the contents of the parent to be the contents of the childeren ...
$(".attribute-pdf").each(function(){
var $this = $(this); // cache for performance
$this.html($this.children());
});
grab the content ( a link ) , empty the div ( removes 1.2 mb ) and again append a link.
http://jsfiddle.net/vpVMK/
var content = $(".attribute-pdf a");
$(".attribute-pdf").html('');
$(".attribute-pdf").append(content);
you could do:
// contents() gives children, all including non-element nodes.
// Then, we can filter those down to the final text one.
var textNodes = $( ".attribute-pdf" ).contents().filter(function() {
return this.nodeType === 3;
});
var lastTextNode = textNodes.last();
//and replace
lastTextNode.replaceWith('');
You could do this:
var children = $(".attribute-pdf").children();
$(".attribute-pdf").html(children);
http://jsfiddle.net/H2WVt/
Here is another method that hasn't been posted yet:
$(".attribute-pdf").html(function(){
var $this = $(this),
$tmp = $('<div>');
return $.makeArray( $this.children('a').map(function() {
$tmp.html(this)
return $tmp[0].innerHTML
}) ).join('')
})
The fiddle

How to add onto a HTML attachment like href=""

So I ran up onto a problem, how would I add text into the HTML attachment href. So, and example:
...
How would I change it too:
...
But, what if I had mutiple of these with different href's:
...
...
...
How would I change them all?
href is called an attribute, and you can use .attr() to change it
If you want to add same prefix to all of them then
jQuery(function () {
$('a').attr('href', function (i, href) {
return 'http://google.com' + href;
});
})
Demo: Fiddle
First find all the elements you wish to change and put them into an array (below, I'm just using all anchor tags, but you could do getElementsByClassName and give them all some class as to not affect every anchor tag on the page), then loop through them and append the code.
(function () {
var anchors = document.getElementsByTagName("a");
for (var x = 0; x < anchors.length; x++) {
anchors[x].href = "http://google.com" + anchors[x].href;
}
})();
If you're appending the same string to the start of all anchor tags' HREF attribute within a particular DIV or other container (say it has ID myDiv), that's relatively easy:
$('#myDiv a').each(function(){
$(this).attr('href', 'http://google.com' + $(this).attr('href'));
});

how to append a div tag generated by jQuery dynamically with a javascript div tag element

I want to append a div tag generated by jQuery dynamically with a javascript div tag element. My code looks like this:
$(".remove_item").click(function(){
$(this).hide("fast", function(){
var id = $(this).parent().attr("id");
var remove_item_id = document.getElementById(id);
var block_element = document.getElementById("block");
block_element.removeChild(remove_item_id);
new_item = $("<div/>");
new_item.attr("id", "item");
new_item.attr("name", "item");
new_item.addClass("div_image");
new_item.append($("<img/>")
.addClass("image")
.attr("src", "/compare/sites/default/files/add_item.jpg")
.attr("height", 50)
.attr("width", 50));
new_item.append($("<span/>")
.addClass("new_item")
.click(function(){
$(this).parent().remove();
}));
block_element.append(new_item);
});
});
The code for appending the jQuery div tag with javascript div tag should look like this:
block_element.append(new_item);
But its giving error since we cannot bind since I am using javascript and jQuery in the same line. Is there any way to do it?
The only thing, you need to change is
var block_element = $("#block");
$("#"+remove_item_id).remove();
Rest should work as it is.
What you need do is you should convert the JavaScript element to a jQuery object.
$(block_element) could convert the JavaScript element to a jQuery object;
contrarily $(block_element)[0] could convert a jQuery object to a JavaScript element.
You only need to pass the element in the jQuery selector.
First solution (when you append) :
$(block_element).append(new_item);
Second solution (when you select your element)
var block_element = $("#block");
$(".remove_item").click(function(){
$(this).hide("fast", function(){
var elm = $("#block"),
parent = $(this).parent(),
img = $('<img src="/compare/sites/default/files/add_item.jpg" class="image" height="50px" width="50px" />'),
span = $('<span class="new_item"></span>'),
new_item = $('<div id="item" name="item" class="div_image"></div>').append(img).append(span);
elm.remove(parent).append(new_item).on('click', function(){ $(this).parent().remove(); });
});

Categories