Is it possible to implement a counter which directly changes the text of a tag using jQuery/Javascript? For example if I had 2 tags:
<a>hello</a>
<a>bye</a>
After running the jQuery/JS function, this is what would happen:
<a>[1]hello</a>
<a>[2]bye</a>
I can't use a CSS counter as I need the script to directly edit the HTML.
You can use .html(function)
$("a").html(function(index, html) {
return "[" + (index + 1) + "]" + html;
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a>hello</a>
<a>bye</a>
You could loop through all the anchors and add the index to the content using .prepend() :
$("a").each(function(index,value) {
$(this).prepend("["+(index++)+"] ");
})
Hope this helps.
$("a").each(function(index,value) {
$(this).prepend("["+(index++)+"] ");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a>hello</a>
<a>bye</a>
With pure JS, you can use create a text node and insert it as the first child node to get the counters - see a demo below:
Array.prototype.forEach.call(document.querySelectorAll("a"), function(e, i) {
e.insertBefore(document.createTextNode(`[${i+1}]`), e.childNodes[0]);
});
<a>hello</a>
<a>bye</a>
Use this code,
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<a>hello</a>
<a>bye</a>
<script>
$("a").html(function(index, data) {
return "[" + (index + 1) + "]" + data;
})
</script>
Related
Any idea how make it with link? I try but nothing
<h3 class="wd-entities-title">WIANEK Amarylis bohaterem</h3>
$(".wd-entities-title").each(function() {
var html = $(this).html().split(" ");
html = html[0] + "<br>" + html.slice(1).join(" ");
$(this).html(html);
});
http://jsfiddle.net/nd46b23L/
The text you want to separate is inside an <a> tag - you should include that in your query or else the first space you'll encounter is the space in the <a> tag.
$(".wd-entities-title a").each(function() {
var html = $(this).html().split(" ");
html = html[0] + "<br>" + html.slice(1).join(" ");
$(this).html(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="wd-entities-title">WIANEK Amarylis bohaterem</h3>
Slightly less verbose approach using html(function) which will iterate over all instances of matching selector <a> exposing the current html for each instance
Then use replace() to insert the break at first space and return the modified string
$(".wd-entities-title a").html((i, curr) => curr.trim().replace(' ', ' <br/>'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h3 class="wd-entities-title">WIANEK Amarylis bohaterem</h3>
I need to display user input inside the div. But if the user put in tag, it will execute whatever inside the script tag.
For example
<html>
<body>
<button onclick="runTest('<script>alert(\'test\')</script>')">Click Me</button>
<div id="test"></div>
</body>
</html>
And my javascript runTest function
function runTest(str) {
$('#test').append($('<div>' + str + '</div>'));
}
If I run this, it will cause alert() to be executed. I tried to use escape(str), but it displays the escape characters %3Cscript%3Ealert%28%27test%27%29%3C/script%3E
Any idea? Here is the fiddler: https://jsfiddle.net/zvLg1w6q/1/
Thanks...
you can use this function:
function htmlencode(str) {
return str.replace(/[&<>"']/g, function($0) {
return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
});
}
and use it same as follow:
function htmlencode(str) {
return str.replace(/[&<>"']/g, function($0) {
return "&" + {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"}[$0] + ";";
});
}
document.getElementById("myDiv").innerHTML = htmlencode('<scrip t>alert("hi")</scrip t>')
<div id="myDiv">
</div>
I am pulling some text from a database and I have , and I would like to replace them with <br> don't really know why it's not working any ideas?
JS Code
$( document ).ready(function() {
//.MoreInfoText
var $infotext = $('.MoreInfoText').text().replace(/\+/g, '<br>');
$.each($infotext, function() {
$('.MoreInfoText').text($infotext);
});
});
Text as its coming from the DB:
Ryan open 30/01/1998, ryan added numberOFIteams of NameOFIteams
1st use replace(/\,/g, '<br>')); yours only replace +
(note the g means replace all, you can also make the search case-insensitive pass the "i" parameter ex: /gi)
2nd use $('.MoreInfoText').html() so your <br> are treated as HTML instead of string.
$( document ).ready(function() {
//.MoreInfoText
$('.MoreInfoText').html($('.MoreInfoText').text().replace(/\,/g, '<br>'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="MoreInfoText">11111,22222,33333,44444,55555</span>
It should be .replace(/,/g,"<br>") so all ,s get replaced with <br>. Right now it's replacing + with <br>.
Also to iterate over every element with class MoreInfoText replacing , with <br> modify your code like this:
$('.MoreInfoText').each(function() {
var text = $(this).text().replace(/,/g, '<br>')
$(this).html(text);
});
Try to use the following code:
$( document ).ready(function() {
//.MoreInfoText
var $infotext = $('.MoreInfoText').text().replace(',', ' ');
$.each($infotext, function() {
$('.MoreInfoText').text($infotext);
});
});
I would recommend avoiding the usage of <br /> for adding line breaks, you may consider using <p> instead.
$( document ).ready(function() {
//.MoreInfoText
$('.MoreInfoText').each(function() {
var moreArray = $(this).text().split(',');
var $infotext = '';
for(var i = 0; i < moreArray.length; i++){
$infotext += '<p>' + moreArray[i] + '</p>';
}
$(this).empty().html($infotext);
});
});
If paragraphs are not already placed each on a new line, you can add a CSS rule for that. This helps separating the content from the presentation, which is what CSS is for.
I'm using blogger as my blogging platform. In my blog homepage, I create a function to grab all images from single post for each post (there are 5 posts in my homepage), then append all images from single post to single slider, for each post.
This is my function script (I place it after <body> tag):
<script type='text/javascript'>
//<![CDATA[
function stripTags(s, n) {
return s.replace(/<.*?>/ig, "")
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(a) {
var p = document.getElementById(a);
img = p.getElementsByTagName("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class='flexslider'><ul class='slides'></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
//]]>
</script>
Then my variable, each post have single variable, different for each post based on it's ID:
<script type='text/javascript'>var x="Post Title",y="http://myblog.url/post-url.html";rm("p8304387062855771110")
My single post markup:
<span id='p8304387062855771110'></span>
The problem is, the append function in my script not work. Am I forget something in my code?
Your jQuery/JavaScript is very ropey. There is no method each on a nodelist. Try not to mix jQuery/JavaScript up so much. And you might consider using a array/join on the html you want to insert to keep the line length readable. That way you might have noticed that your HTML quotes were not consistent.1
var $p = $('#' + a);
$p.find('img').each(function () {
var html = $('<li>').append($(this))
$('.flexslider .slides').append(html);
});
var html = [
'<div class="entry-container"><div class="entry-content">',
'<div class="entry-image"><div class="flexslider">',
'<ul class="slides"></ul></div></div><div class="entry-header">',
'<h1><a href="',
y,
'">',
x,
'</a></h1></div><p>',
stripTags(p.innerHTML, SNIPPET_COUNT),
'</p></div></div>'
].join('');
$p.html(html);
1 Personally I prefer single quotes for JS work and double quotes for HTML attributes and never the twain shall meet.
I think <li> doesnt work try li like this:
$(".flexslider .slides").append($("li").append(this));
You could get rid of type="text/javascript" and //<![CDATA[, it is 2014, after all ;-)
Also, .*? is not what you mean.
<script>
function stripTags(s, n) {
return s.replace(/<[^>]*>/g, "") // Be careful with .*? : it is not correct
.split(/\s+/)
.slice(0, n - 1)
.join(" ")
}
function rm(id) {
var $p = $('#' + id);
img = $p.find("img").each( function(){
$(".flexslider .slides").append($("<li>").append(this));
});
p.innerHTML = '<div class="entry-container"><div class="entry-content"><div class="entry-image"><div class="flexslider"><ul class="slides"></ul></div></div><div class="entry-header"><h1>' + x + '</h1></div><p>' + stripTags(p.innerHTML, SNIPPET_COUNT) + '</p></div></div>'
}
</script>
I am pulling in tweets through a getJSON and writing them to a Google map infowindow with javascript. The problem is, these tweets come with text links but no formatting (and no ids/classes/anything for which to narrow a find and replace). This is the mash of code I'm using right now to find the text, but I can't get it to wrap whatever it finds in <a> tags to properly display the links:
function wrap( str ) {
return '<a href="' + str + '">' + str + '<\/a>';
};
function replaceText() {
var jthis = $(this);
$("*").each(function () {
if (jthis.children().length == 0) {
jthis.text(jthis.text().replace(/\bhttp[^ ]+/i, wrap));
}
});
}
$(document).ready(replaceText);
$("html").ajaxStop(replaceText);
Did I overlook something or does anyone know a better way to do this?
If i understand your problem right, this should work.
not sure why you are iterating through elements as regexp will scan all the text anyway.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
<script>
function wrap( str ) {
return '<a href="' + str + '">' + str + '<\/a>';
};
function replaceText() {
$(".tweet").each( function(){
$(this).html($(this).html().replace(/\bhttp[^ ]+/ig, wrap));
})
}
$(document).ready(replaceText);
</script>
</head>
<body>
<div class="tweet"> test 1 http://example.com/path </div>
<div class="tweet"> test 2 http://example.com/path </div>
</body>
</html>