js How to add href + text onclick - javascript

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

Related

Dynamically add new element and change its content

I want to "copy" a certain elements and the change some of the text inside them with a regex.
So far so good: (/w working fiddle - http://jsfiddle.net/8ohzayyt/25/)
$(document).ready(function () {
var divs = $('div');
var patt = /^\d\./;
var match = null;
for (i = 0; i < divs.length; i++) {
match = ($(divs[i]).text().match(patt));
$(divs[i]).text($(divs[i]).text().replace(match[0], "5."));
}
});
HTML
<div>1. peppers</div>
<div>2. eggs</div>
<div>3. pizza</div>
This works exactly the way I want it, but I want to add some of the content dynamically, but when I try to change the content of the copied divs, nothing happens.
Please refer to this fiddle:
http://jsfiddle.net/8ohzayyt/24/
I have put some comments, to be more clear what I want to achieve.
I thing that your problem is that you're not passing an element to your changeLabel function, but just a string.
Look at this solution: http://jsfiddle.net/8ohzayyt/26/
Here is the line I changed to make your code work:
var newContent = $("<hr/><div id='destination'>" + $("#holder").html() + "</div>");
I just wrapped your HTML in $(). this creates an element from the string.
try:
var newContent = $("<hr/><div id='destination'>" + $("#holder").html() + "</div>");
EDIT:
Brief explanation What I've done.
In order to make $(el).find('div'); work changeLabel() needs an element. Instead of passing newContent as a string doing the above will make it pass as an element which will make $(el).find('div'); work.

jQuery remove certain tags from a string

I have a string where I want to remove all figure tags. I have tried the following:
var s = '<html><body>report content<figure id="fig2" data-contenttype="chart"><img src="chart.jpg"/><div>chart 1</div></figure><div>body content</div><figure id="fig2"><img src="chart2.jpg"/><div>chart 2</div></figure></body></html>';
var result = $(s).find('figure').remove();
The reason this does not work is that find does not find the figure elements because they have children. Does anyone know how I can remove all figure nodes (and everything inside them) and leave the rest of the html in tact?
Note the html is not in the DOM I need to do this via string manipulation. I don't want to touch the DOM.
You can wrap your string in a jQuery object and do some sort of a manipulation like this:
var removeElements = function(text, selector) {
var wrapped = $("<div>" + text + "</div>");
wrapped.find(selector).remove();
return wrapped.html();
}
USAGE
var removedString = removeElements('<html><body>report content<figure id="fig2" data-contenttype="chart"><img src="chart.jpg"/><div>chart 1</div></figure><div>body content</div><figure id="fig2"><img src="chart2.jpg"/><div>chart 2</div></figure></body></html>','figure');
The beauty of this approach is that you can specify a jquery selector which to remove.
Another approach for keeping html and body tag:
var s = '<html><body>report content<figure id="fig2" data-contenttype="chart"><img src="chart.jpg"/><div>chart 1</div></figure><div>body content</div><figure id="fig2"><img src="chart2.jpg"/><div>chart 2</div></figure></body></html>';
var $s = s.replace(/<figure>(.*)<\/figure>/g, "");
console.log($s)

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/

(jquery) change nested same html tag to other bbcode tag

ok here is what i have:
<div id="mydiv">
<font color="green"><font size="3"><font face="helvetica">hello world</font></font></font>
</div>
I know the tags are strange, but that's what produced by the website.
So basically I want to change the font tag to bbcdoe tag, the jquery code I wrote:
$("#mydiv").find("font").text(function(){
var text = $(this).text();
var size = $(this).attr("size");
var color = $(this).attr("color");
var face = $(this).attr("face");;
if(size!=undefined){
return '[size="'+size+'"]'+text+'[/size]';
}
if(color!=undefined){
return '[color="'+color+'"]'+text+'[/color]';
}
if(face!=undefined){
return '[type="'+face+'"]'+text+'[/type]';
}
});
so what I got is only: [color="green"] hello world [/color]. always only the first tag. any idea?
ps: I tried each, replaceWith, html(), all the same result. only the first tag is change.
The reason it doesn't work is because when you call
$("#mydiv").find("font").text("New text")
For each font tag, starting from the first tag, it will replace the text within that tag.
Here is an example to show you what's going on.
Example | Code
$fonts = $("font","#mydiv");
console.log($fonts.text());
$fonts.text(function(){
return "New text";
});
console.log($fonts.text());
Here is an example of how you could do it instead
Example | Code
jQuery.fn.reverse = [].reverse;
var attributes= ["size", "color", "face"];
var text = $.trim($("#mydiv").text());
$("font","#mydiv").reverse().each(function(i, e) {
for (var i = 0; i < attributes.length; ++i){
var attr = $(e).attr(attributes[i]);
if( typeof attr != "undefined")
text = "["+attributes[i]+"="+attr+"]"+text+"[/"+attributes[i]+"]";
}
});
$("#mydiv").text(text);
A room full of sad, wailing kittens wishes that you'd get rid of those <font> tags, but you could probably make it work by explicitly working your way down through the nested tags.
It does what it does now because the outer call to .text() runs for the very first <font> tag, and it obliterates the other tags.
edit — to clarify, when you call
$('#mydiv').find('font')
jQuery will find 3 font tags. The library will therefore call the function you passed into .text() for each of those elements. However, the first call will have the effect of removing the other two <font> elements from the DOM. Even though the library proceeds to call your callback for those elements, there's no effect because they're not on the page anymore.
Here's what could work:
var $fonts = $('#mydiv').find('font');
var text = $fonts.text();
var attrs = {};
$fonts.each(function(_, font) {
var names = ["size", "color", "face"];
for (var i = 0; i < names.length; ++i)
if (font[names[i]]) attrs[names[i]] = font[names[i]];
});
var newText = "";
for (var name in attrs) {
if (attrs.hasOwnProperty(name))
newText += '[' + name + '=' + attrs[name] + ']';
}
newText += text;
for (var name in attrs) {
if (attrs.hasOwnProperty(name))
newText += '[/' + name + ']';
}
$('#mydiv').text(newText);
Note that I'm not really sure why you want to put the BBCode onto the page like that, but it seems to be the intention.
Seems to me your first line should be:
$("#mydiv").find("font").each(function(){

Read more/less without stripping Html tags in JavaScript

I want to implement readmore/less feature. i.e I will be having html content and I am going to show first few characters from that content and there will be a read more link in front of it. I am currently using this code :
var txtToHide= input.substring(length);
var textToShow= input.substring(0, length);
var html = textToShow+ '<span class="readmore"> … </span>'
+ ('<span class="readmore">' + txtToHide+ '</span>');
html = html + '<a id="read-more" title="More" href="#">More</a>';
Above input is the input string and length is the length of string to be displayed initially.
There is an issue with this code, suppose if I want to strip 20 characters from this string:
"Hello <a href='#'>test</a> output", the html tags are coming between and it will mess up the page if strip it partially. What I want here is that if html tags are falling between the range it should cover the full tag i.e I need the output here to be "Hello <a href='#'>test</a>" . How can I do this
Why not just hide the hidden part of the content instead of adding it later? I usually just use a display: none for hidden content and have it set to display: block when the read more is clicked..
Edit:
I'm sorry I didn't read the question good enough.
This should work though:
<div id="test">
This links to google
<strong>and</strong> some random text to make it a little bit longer!
</div>
<script type="text/javascript">
$(document).ready(function() {
var max_length = 21;
var text_to_display = "";
var index = 0;
var full_contents = $("#test").contents();
// loop through contents, stop after maxlength is reached
$("#test").contents().each(function(i) {
if ($(this).text().length + text_to_display.length < max_length) {
text_to_display += $(this).text();
index++;
} else {
return false;
}
});
// second loop removes unwanted content
$("#test").contents().each(function(i) {
if (i > index) {
$(this).remove();
}
return true;
});
// add link to show the full text
$('read more...').click(
function(){
$("#test").html($(full_contents));
$(this).hide();
}).insertAfter($("#test"));
});
</script>
This can be accomplished quite easilly using jQuery
<div id="test">This is a link to google</div>
<script type="text/javascript">
$(document).ready(function() {
alert($("#test").text());
});
</script>
Good luck!
You stated that the html tags would become an issue, so why not remove in the string conversion and replace with plain text, then on the Show More click, Toggle plain + Html
$(document).ready(function(){
var Contents = $('#post p'); //Object
var Plain = Contents.text(); //truncate this
//Hide the texts to Contents
Contents.hide();
var PlainContainer = $("<div>").addClass("Plain_Container").val(Plain)
//Add PlainContainer div after
Contents.append(PlainContainer);
var $('.show_hide').click(function(){
$(Plain_Container).remove(); //Delete it
Contents.Show(); //Show the orginal
$(this).remove(); //Remove the link
return false; //e.PreventDefault() :)
});
});
This way using the text() function will convert html tags to there values and remove the tag itself, all you have to do is toggle them :)
Note: The code above is not guaranteed to work and is provided as example only.

Categories

Resources