How to swap link with data value with javascript or jQuery - javascript

How do I swap this:
var message = 'Another hurricane is coming <a contenteditable="false" data-number="23">here</a>. And check out pictures <a contenteditable="false" data-number="43">over there</a>.';
Into this:
message = 'Another hurricane is coming #[23]. And check out pictures #[43].';
What I have so far:
var swap = function(message) {
message.each(function() {
var text = '#[' + $(this).data(number) + ']';
message = $(this).replaceWith(text);
});
return message;
}
Thanks for your help!

This tiny regular expression could fix that for you:
message = message.replace(/<a contenteditable="false" data-number="(\d+)">.+?<\/a>/g, '#[$1]');
Or as the required function:
var swap = function (message) {
return message.replace(/<a contenteditable="false" data-number="(\d+)">.+?<\/a>/g, '#[$1]');
}
A more flexible/dynamic version
message = message.replace(/<a.+?data-number=(?:"|')(\d+)(?:"|').+?<\/a>/g, '#[$1]');
This will work with any amount of attributes of <a> and even accept digits from both data-number="" and data-number=''. Doesn't get more flexible than that. Or does it? :-)

Try
var message = 'Another hurricane is coming <a contenteditable="false" data-number="23">here</a>. And check out pictures <a contenteditable="false" data-number="43">over there</a>.';
var swap = function(message) {
var msg = $.parseHTML(message)
, message = msg[0].textContent
+ "#[" + msg[1].dataset.number + "]"
+ msg[2].textContent
+ "#[" + msg[3].dataset.number + "]";
return message
};
var message = 'Another hurricane is coming <a contenteditable="false" data-number="23">here</a>. And check out pictures <a contenteditable="false" data-number="43">over there</a>.';
var swap = function(message) {
var msg = $.parseHTML(message)
, message = msg[0].textContent
+ "#[" + msg[1].dataset.number + "]"
+ msg[2].textContent
+ "#[" + msg[3].dataset.number + "]";
return message
}; var _message = swap(message); document.write(_message)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

You can create a temp disconnected element and use jQuery selectors to manipulate the HTML in a structured way. This has no DOM overhead and makes processing the HTML very convenient. It will also work if the attributes on the anchors ever differ from the example shown as it does not try to exact match:
Final shorter function version now brought to the top:
JSFiddle: http://jsfiddle.net/xbm2h6aL/5/
var swap = function (message) {
var element = $('<div>').html(message);
var $anchors = element.find('a').each(function () {
$(this).replaceWith("#[" + $(this).data('number') + "]");
});
return element.html();
}
Older versions below:
JSFiddle: http://jsfiddle.net/xbm2h6aL/1/
Note: the display div was purely for testing purposes, to show it worked.
var message = 'Another hurricane is coming <a contenteditable="false" data-number="23">here</a>. And check out pictures <a contenteditable="false" data-number="43">here</a>.'
// create a disconnected div with the content
var element = $('<div>').html(message);
var $anchors = element.find('a');
$anchors.each(function(){
var $a = $(this);
var n = $a.data('number');
$a.replaceWith("#[" + n + "]");
});
$('#result').append(element.contents());
The code can be shortened by a line or two, but I wanted it to be instructional :)
As a function (like the original): http://jsfiddle.net/xbm2h6aL/3/
var message = 'Another hurricane is coming <a contenteditable="false" data-number="23">here</a>. And check out pictures <a contenteditable="false" data-number="43">here</a>.'
var swap = function (message) {
// create a disconnected div with the content
var element = $('<div>').html(message);
var $anchors = element.find('a');
$anchors.each(function () {
var $a = $(this);
var n = $a.data('number');
$a.replaceWith("#[" + n + "]");
});
return element.html();
}
$('#result').append(swap(message));

Here's a code using jQuery native functions and without RegExp:
var message = 'Another hurricane is coming <a data-number="23">here</a>. And check out pictures <a data-number="43">here</a>.';
var swap = function(msg){
var html = jQuery.parseHTML(msg);
var result = '';
$.each(html, function(i, el){
var element = $(el).filter('a');
if(element.length > 0){
var number = element.data('number');
var text = '#[' + number + ']';
result += text;
} else {
result += $(el).text();
}
});
return result;
}
swap(message);
You shouldn't rely on RegExp because you might have several attributes for the HTML elements you're using.
Here's a JSFiddle: http://jsfiddle.net/g3k3ovd4/

Related

Search strings of an array in content of several div referenced by class and perform action depending on the condition

I have this basic code for the development of what I need, who can help me is a lot of help for me !!
note: I used the function .search () and replace () without getting good results, I do not know what else way to take
var fjstr = document.getElementsByClassName("js-product-variants-list");
var fjinnerColor = '';
var fjscolor2 = ["Rojo-Wengue",
"Aqua-Natural",
"Gris/Decape",
"Rosa-Blanco",
"Turqueza-Wengue",
"Turqueza-Blanco",
"Naranja-Natural",
"Amarillo-Natural"];
var resultado = "";
var pos = -1
fjscolor2.forEach(function(element) {
pos = fjstr.innerHTML.search(element.toString());
if(pos!=-1){
resultado += "<a href='#" + (fjscolor[i]) + "' ><li class='fj-product-color-icon' id='color-" + (fjscolor[i]) + "'></li></a>"
document.getElementsByClassName('cont-product-variacion-color')[0].firstElementChild.innerHTML = resultado;
}
});

Create hyperlink with js dom

I'm trying to create a wikipedia viewer, get json data and then show it with a hyperlink that take you to the article. The problem is when I want to give the href attribute to a specific element.
$.getJSON(url1 + search + url2, function(data) {
for(i=0; i<data[1].length; i++) {
var p = document.createElement("P");
var id = p.setAttribute("id", i);
var t = document.createTextNode(data[1][i] + ': ');
var text = document.createTextNode(data[2][i]);
var a = document.getElementById(i);
var link = a.setAttribute("href", data[3][i]);
p.appendChild(t);
p.appendChild(text);
p.appendChild(link);
document.body.appendChild(p);
}
});
So, I'm calling the specific "p" element by Id(i value) and then I append to it the specific url. What am I missing?
It actually doesn't make much sense trying to correct parts of your code. The following is a cleaned up and corrected version of yours. Although it is untested, it should produce a format like <p>data[1][i]: data[2][i]</p>.
$.getJSON(url1 + search + url2, function(data)
{
for(var i = 0; i < data[1].length; ++i)
{
//main element
var p = document.createElement("p");
p.id = "element" + i; //you should not use just numbers as IDs
//preceding description
var t = document.createTextNode(data[1][i] + ': ');
//actual link
var text = document.createTextNode(data[2][i]);
var a = document.createElement("a");
a.href = data[3][i];
a.appendChild(text);
//merge all of them together
p.appendChild(t);
p.appendChild(a);
document.body.appendChild(p);
}
});
You are using
p.appendChild(link);
You should be using:
p.appendChild(link);
I think that's not the only thing wrong, your var a = document.getElementById(i); assumes you have an element in the DOM with ids looking like "1" 'var a = document.createElement(a);
$.getJSON(url1 + search + url2, function(data){
for(i=0; i<data[1].length; i++){
var p = document.createElement("p");
var t = document.createTextNode(data[1][i] + ': ');
var text = document.createTextNode(data[2][i]);
var a = document.getElementById(i);
var link = a.setAttribute("href", data[3][i]);
a.appendChild(t);//put text inside the clickable link
a.appendChild(text);//put additional text inside the clickable link
p.appendChild(a);//put the link inside the <p> element
document.body.appendChild(p);//add the link into the DOM at the end of the body
});
//now your element is a <p>data[1][i]: data[2][i]</p>

Javascript: Unable to load image resource on a div tag

Can anyone please give me an idea on how to view the actual image resource on a div tag:
This is the complete script:
var smileys = [];
smileys[":)"] = "happy.png";
smileys[":D"] = "laugh.png";
smileys[":3"] = "meow.png";
smileys[":{"] = "must.png";
smileys[":V"] = "pac.png";
smileys[":("] = "sad.png";
smileys[":O"] = "surprised.png";
smileys[":?"] = "wat.png";
function RegExpEscape(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
function replaceEmoticons(str) {
for (var key in smileys) {
var re = new RegExp("(?:^|\\s)" + RegExpEscape(key) + "(?=$|\\s)", 'g');
var str2 = "<img src='images/smileys/" + smileys[key] + "'/>";
//alert(re);
//alert(str2);
var inputName = document.getElementById("input");
alert(inputName);
str = str.html().replace(re, str2);
}
return (str);
}
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
update();
function update() {
$('#result').text(replaceEmoticons($('#input').val()));
}
$('#input').keyup(function() {
delay(update, 250);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4>Input :</h4>
<textarea id="input">
Hello how are you all doing today? :)
</textarea>
<hr>
<h4>Result :</h4>
<div id="result">
</div>
When I inspect element no error was found on the console!
Kindly Assist!
Note that the javascript code is executing before the DOM is loaded. When you load page, after loading the code is executing and #input doesn't exist yet. Put it in a $(document).ready, or in a onload event.
$(document).ready(function() {
//your stuff
});
EDIT
See that fiddle: https://jsfiddle.net/aoaugpaf/
In this function:
function replaceEmoticons(str) {
for (var key in smileys) {
var re = new RegExp("(?:^|\\s)" + RegExpEscape(key) + "(?=$|\\s)", 'g');
var str2 = "<img src='images/smileys/" + smileys[key] + "'/>";
//alert(re);
//alert(str2);
var inputName = document.getElementById("input");
alert(inputName);
str = str.html().replace(re, str2);
}
return (str);
}
str doesn't have an html() method since it's the value of an input as you wrote here:
$('#result').text(replaceEmoticons($('#input').val()));
Simply remove the html() method and everything will work.
Here's a fiddle I've made for you.
Because $().val() returns String and string has no method .html()
Edit function replaceEmoticons:
str = str.replace(re, str2);
It works: http://jsfiddle.net/au419fkh/

Javascript button.onclick not functioning like I thought

So I was in the presumption that this function
button.onclick = exampleFunk;
would give me a handler on each button when I click them, but it doesn't. When replacing it with:
button.onclick = alert("bananas");
I'm getting alerts at page onload. The problem is already solved with this:
button.setAttribute("onclick", "removeIssue(this)");
Out of curiousity... What's going on?
edited layout of post
EDIT
var issues = [];
window.onload = function () {
//alert("venster geladen");
issuesToList()
}
function issuesToList(data) {
/*alert(
"array length is " + data.issues.length + "\n" +
"total_count is " + data.total_count + "\n" +
"limit is " + data.limit + "\n" +
"offset is " + data.offset + "\n" + ""
);*/
for (i = 0; i < data.issues.length; i++) {
issue = data.issues[i];
createIssue(issue);
}
}
function createIssue(issue){
var id = issue.id;
var tracker = issue.tracker;
var status = issue.status;
var priority = issue.priority;
var subject = issue.subject;
var description = issue.description;
var assignee = issue.assignee;
var watchers = issue.watchers;
var ticket = new Issue(id, tracker, status, priority, subject, description, assignee, watchers);
issues.push(ticket);
var button = document.createElement("button");
button.innerHTML = "-";
button.onclick = function (){ alert("bananas")};
//button.setAttribute("onclick", "removeIssue(this)");
var item = document.createElement("div");
item.setAttribute("id", id);
item.appendChild(button);
item.innerHTML += " " + subject;
var container = document.getElementById("container");
container.appendChild(item);
}
function removeIssue(e){
var key = e.parentNode.getAttribute("id");
var count = issues.length;
if(confirm("Confirm to delete")){
for(i=0; i<count; i++){
if (issues[i].id == key ){
issues.splice(i,1);
var element = document.getElementById(key);
element.parentNode.removeChild(element);
}
}
}
}
function Issue(id, tracker, status, priority, subject, description, assignee, watchers){
this.id = id;
this.tracker = tracker;
this.status = status;
this.priority = priority;
this.subject = subject;
this.description = description;
this.assignee = assignee;
this.watchers = watchers;
}
EDIT
<body>
<h1>List of Issues</h1>
<div id="container"></div>
<script src="http://www.redmine.org/issues.json?limit=10&callback=issuesToList"></script>
</body>
You need to mask the alert in a function:
button.onclick = function (){ alert("bananas")};
As such:
var btn = document.createElement("BUTTON");
var t = document.createTextNode("CLICK ME");
btn.appendChild(t);
btn.onclick = function() {alert("bananas")};
document.body.appendChild(btn);
Whats going on?
You alert() is executed on page load because its a function call. When the execution of your script reaches that line your assignment
button.onclick = alert("bananas");
is actually executing the alert statement and not assigning it to button.onclick
You can bind arguments to the function so that it returns with the function you want it to call using your arguments (with additional arguments passed later added on to the end). This way doesn't require writing extraneous code (when all you want to do is call a single function) and looks a lot sleeker. See the following example:
button.onclick = alert.bind(window, "bananas");
An unrelated example of how it works in your own code is like this:
var alert2 = alert.bind(window, 'Predefined arg');
alert2(); // 'Predefined arg'
alert2('Unused'); // 'Predefined arg'
For IE, this requires IE9 as a minimum. See MDN for more information.
EDIT: I've looked closer at your code and there was one significant change that was needed for it to work... You cannot add onto the innerHTML when you've added JavaScript properties to a child element. Changing the innerHTML of the parent element will convert your element into HTML, which won't have the onclick property you made before. Use element.appendChild(document.createTextNode('My text')) to add text dynamically.
See a functioning example here: http://jsfiddle.net/2ftmh0gh/2/

Variable of a function are shared between different instance of that same function,my variable a'rent local to it's instance?

I made a function to add <a> tag in chat text and it worked fine, but it seems the variables of the function are shared between different instances of the function called from different chat rooms. I thought function variable were local, can anyone explain why I'm encountering this problem? Well I found out the code was wrong and a <p> tag the ajax function was adding to the string was interfering with this function. i fixed it by adding a space before the conflicting <p> tag and now it works fine...updated the code with english variable names too :)
function ajoutertagdelien(dataChat)
{
if (dataChat)
{
}
else
{
dataChat = " ";
}
var chatsendvar = dataChat;
var linkLocation, chatStringLeftPiece, chatfinal = "", chatStringRightPiece, lienfin, LinkAlone, LinktagString, LinkPiece;
var linkTagA = new Array();
var variablelocation = new Array();
var variablechatsend = new Array();
var increment=0;
var earlierLinkLength = 0;
linkLocation = chatsendvar.indexOf("www.");
while (linkLocation != -1) {
increment++;//
if (linkLocation != -1)
{
chatStringLeftPiece = chatsendvar.substring(0,linkLocation);
LinkPiece = chatsendvar.slice(linkLocation,chatsendvar.length);
lienfin = LinkPiece.indexOf(" ");
LinkAlone = LinkPiece.substring(0,lienfin);
chatStringRightPiece = chatsendvar.substring(((lienfin + linkLocation)),chatsendvar.length) ;
console.log( chatStringLeftPiece + " droit et gauche " + chatStringRightPiece + " number of theloop in the while=" + increment);
LinktagString = "<a target='_blank' href='http://"+ LinkAlone+"'>"+LinkAlone+"</a>";
chatsendvar = chatStringLeftPiece + " " + chatStringRightPiece;
linkTagA.push(LinktagString);
variablelocation.push(chatStringLeftPiece.length + earlierLinkLength);
earlierLinkLength = earlierLinkLength + LinktagString.length +1;
}
linkLocation = chatsendvar.indexOf("www.");
}
for (var x = 0, j = linkTagA.length; x<j; x++) {
chatsendvar = chatsendvar.split('');
chatsendvar.splice((variablelocation[x]),1," "+linkTagA[x]+" ");
chatsendvar = chatsendvar.join('');
};
return chatsendvar;
}
All this code to detect links in a text?
I know that's not what you asked, but this small function can do this. It can detect links beginning with www. or http:// and even handles url parameters, like ?a=1&b=2. Here is a demo fiddle.
The regex could be modified to handle https:// or url encoding for example, but you get my point.
function makeLinks(text) {
return text.replace(/(?:http:\/\/|(www\.))([\w\d.\/\?&=]+)/gi, '<a target="_blank" href="http://$1$2">$1$2</a>');
}

Categories