Get initial and final position of text inside an element? - jQuery - javascript

I'm trying to learn some of jQuery/JS and I get a problem that I can't solve. I have one text like this:
blablablabla <b data-start="" data-end="">#foo</b> blablabla"
Note that I can have more than one tag in this text.
I need edit the attributes to their right values, so I was constructing a method to do this:
// "str" isn't static, but for pratical purposes, I'm using this as static.
str = 'blablablabla <b data-start="" data-end="">#foo</b> blablabla'
str.children('b').each(function(i){
$(this).attr('data-start', '');
$(this).attr('data-end', '');
})
As you can see, I don't have idea how I can do the code above. I though use:
str.children('b').each(function(i){
var start = $(this).indexOf('#');
$(this).attr('data-start', '');
$(this).attr('data-end', '');
})
But this will return the index 1, because I'm getting the index of text inside the b tag, and not inside the all text itself. So, how I can fix this problem and get initial position of "b" and final position of "b" (excluding the tag itself)?

umm.. something like this perhaps.. jsfiddle link
<span id="test" >
blablablabla <b data-start="" data-end="">#foo</b> blablabla"
</span>
and the jquery..
var str = $("#test").text();
var strB = $("#test b").text();
$("#test b").attr("data-start", str.indexOf(strB) );
$("#test b").attr("data-end", (str.indexOf(strB) + strB.length-1));
alert($("#test").html())

Related

access DOM and change element font and colour

I want to access some character from string and change the style of them
for example "hello"
i want to change "h" character's color and font
how can i do this
i try this
var txt=document.getElementById('d1').getElementsByTagName('p')[0]
txt.innerHTML="H"
txt.style.color="red"
document.getElementById('di') selects a single element from the dom.
You don't need .getElementsByTagName('p')[0] after that.
The solution depends on the dom. If you have an element like
<span id='d1'>H</span>, then the following is correct
var txt = document.getElementById('d1');
txt.innerHTML="H";
txt.style.color="red";
If you want first character of the string and change its color and font (which i am getting from your question), you can do something like :
var text_array = document.getElementById('d1').getElementsByTagName('p')[0].textContent.split("");
text_array[0] = "<span style='color:green; font-family:Arial'>"+text_array[0]+"</span>";
document.getElementById('d1').getElementsByTagName('p')[0].innerHtml = text_array.join("");
<div id="d1">
<p>loading.....</p>
</div>
var txt=document.getElementById('d1').getElementsByTagName('p')[0] var edit=txt.innerHTML//ocnvertobject to string
var len=txt.innerHTML.length
var index=0 //container for scroll the string and change style each corrector
txt.innerHTML=edit[index].toUpperCase().fontsize(150).fontcolor("red")+edit.slice(index+1,len)
++index
i with this code edit corrector of my string

wrap href link and id to last 3 characters in span

I want to wrap a href with and id to the last three characters wrapped in a span.
HTML
<span id="cartCost">€0.00 EUR</span>
The last three characters of the span will always be a currency code. The currency code will change automatically depending on your region. I am trying to wrap the last three characters (currency code) in a href. The href will be used to stimulate a select box and does not need a link just an ID (so even wrapping it the code in a div is sufficient).
I know I need to be working with .each(), .wrapInner and maybe substring. Anyway here is what I've been trying:
$('#cartCost').each(function() {
var count = $(this).text( text.substring(-3)
code = $(count).text();
$(code).wrapInner('<a href="#" id="open">');
})​
The end result should look like this:
<span id="cartCost">€0.00 EUR</span>
Any solutions, greatly appreciated.
1st id must be unique .. use classes instead
2nd:
$('.cartCost').each(function() {
// get the text and use trim to avoid left and right white spaces
var count = $.trim($(this).text());
// get last three .. substring() needs start index and end index
var lastthree = count.substring(count.length - 3 , count.length);
// replace last three with html code we want
var replaceit = count.replace(lastthree , ''+ lastthree +'');
// append the new value as a html using .html()
$(this).html(replaceit);
})
Working Demo
Hey after playing a little with a fiddle, this is the result I could come up with
<script>
$(document).ready(function(){
var content = $('#cartCost').html();
var code = content.substr(-3);
var newCode = "<a href='#' id='open'>" + code + "</a>";
var newContent = content.replace(code, newCode);
$('#cartCost').html(newContent);
});
</script>
<span id="cartCost">€0.00 EUR</span>
Here is the working fiddle

How to replace only the text of this element with jQuery?

I'm trying to make a kind of simple search engine, where
the user enters a string and if it's equal to the text inside
an element, that portion of text must be highlighted some way.
This is the html:
<input type="text">
<input type="button" value="Change text"><br>
Click here to get more info!
this is the css:
.smallcaps{
color:red;
}
and this is the jquery function that makes the search and replace:
$("input[type='button']").click(function(){
var textValue = $("input[type=text]").val();
$("a").html(function(_, html) {
return html.replace(new RegExp(textValue,"ig"), '<span class="smallcaps">'+textValue+'</span>');
});
});
This is an example of how it looks like:
Everything works fine, until the search string is equals to the name of a node element, so for example if the search string is a, the html will be broken.
How can I avoid the replace of the html itself?. I just want to work over the text.
This is the codepen:
http://codepen.io/anon/pen/mefkb
Thanks in advance!
I assume that you want to only highlight the last search and not store the ones from before.
With this assumption, you can store the old value if it is the first call and use the stored value in the calls afterwards:
$("input[type='button']").click(function(){
// Escape the html of the input to be able to search for < or >
var textValue = $('<div/>').text($("input[type=text]").val()).html();
if(textValue === '') return;
$("a").html(function(_, html) {
var old = $(this).data('content');
if(!old) {
old = html;
$(this).data('content', old);
}
var replacer = function(match) {
return match.replace(new RegExp(textValue, "ig"), '<span class="smallcaps">'+textValue+'</span>');
};
if(/[<>]/.test(old)) {
return old.replace(/^[^<>]*</gi, replacer).replace(/>[^<>]*</gi, replacer).replace(/>[^<>]*$/gi, replacer);
}
return replacer(old);
});
});
Also i fixed two bugs I found when testing:
if you search for an empty string, everything is broken.
If you search for html characters like < or > nothing is found as in the text they are converted to < or >.
One thing is not solved, as it is not possible to easily implement it without destroying the subelement structure: It is not possible to search in different subelements, as you have to remove the tags, search then and insert the tags at the right position afterwards.
Working fiddle: http://codepen.io/anon/pen/KlxEB
Updated Demo
A workaround would be to restore <a> to original text, instead of complicating the regex.
Your problem is a form the <span> tag is getting replaced.
var init = $("a").text(); //save initial value
$("input[type='button']").click(function(){
$('a').text(init); //replace with initial value
var textValue = $("input[type=text]").val();
$("a").html(function(_, html) {
return html.replace(new RegExp(textValue,"ig"), '<span class="smallcaps">'+textValue+'</span>');
});
});

Replace text with HTML element

How can I replace a specific text with HTML objects?
example:
var text = "some text to replace here.... text text text";
var element = $('<img src="image">').event().something...
function ReplaceWithObject(textSource, textToReplace, objectToReplace);
So I want to get this:
"some text to replace < img src...etc >.... text text text"
And I would like manipulate the object element without call again $() method.
UPDATE:
I solved.
thanx #kasdega, i made a new script based in your script, because in your script i can't modify the "element" after replace.
This is the script:
$(document).ready(function() {
var text = "some text to replace here.... text text text";
var element = $('<img />');
text = text.split('here');
$('.result').append(text[0],element,text[1]);
$(element).attr('src','http://bit.ly/mtUXZZ');
$(element).width(100);
});
I didnt know that append method accept multiples elements.
That is the idea, only need to automate for multiple replacements
thanx to all, and here the jsfiddle
do a split on the text you want to replace then use the array indexes 0 and 1...something like:
function ReplaceWithObject(textSource, textToReplace, objectToReplace) {
var strings = textSource.split(textToReplace);
if(strings.length >= 2) {
return strings[0] + objectToReplace.outerHTML() + strings[1];
}
return "";
}
UPDATE: I found another SO post Get selected element's outer HTML that pointed me to a tiny jquery plugin that helps here.
I believe this jsfiddle has what you want. outerHTML is the tiny jquery plugin I included in the JSFiddle.
You can also use replace which will reduce some code: http://jsfiddle.net/kasdega/MxRma/1/
function ReplaceWithObject(textSource, textToReplace, objectToReplace) {
return textSource.replace(textToReplace, objectToReplace.outerHTML());
}
function textToObj (text,obj,$src){
var className = "placeholder-"+text;
$src.html($src.html().replace(text,"<div class='"+className+"'></div>"));
$("."+className).replace(obj);
}
you can use $(selector).outerHtml to get the html string of an element
You can replace the html directly: http://jsfiddle.net/rkw79/qNFKF/
$(selector).html(function(i,o) {
return o.replace('old_html','new_html');
})

highlite text parts with jquery, best practice

i have a list of items containig names.
then i have a eventlistener, which ckecks for keypress event.
if the user types i.g. an A all names starting with an A should be viewed with the A bold. so all starting As should be bold.
what is the best way using jquery to highlite only a part of a string?
thanks for your help
Here's a function you can call during your keypress event to highlight a search string:
function Highlight(search)
{
$('ul > li').each(function() {
if (this.innerHTML.indexOf(search) > -1)
{
var text = $(this).text();
text = text.replace(search, "<span id='highlight' style='font-weight: bold'>" + search + "</span>");
$(this).html(text);
}
else
{
this.innerHTML = $(this).text();
}
});
}
Test html:
<ul id='list'>
<li>Bob Jones</li>
<li>Red Smith</li>
<li>Chris Edwards</li>
</ul>
It's not quite as elegant as Pointy's answer, but it handles the matching strings requirement.
There are jQuery plugins to do text highlighting, but I've not seen one that highlights parts of words.
One possible solution would be to put all your names on the page with the first letter surrounded by a <span> tag, with a class:
<span class='A FL'>A</span>ugustine
<span class='C FL'>C</span>arlos
You can then use jQuery to fiddle with those by class name.
$('whatever').keypress(function(ev) {
var k = e.which.toUpperCase();
$('#textContainer span.FL').css('font-weight', 'normal');
$('#textContainer span.' + k).css('font-weight', 'bold');
});
Note that bold characters are fatter than normal characters, so this is going to have a "wiggly" effect that your users might not like. You might consider changing color instead.
thanks for your help...
i figured it out and the detailed resolution comes here:
var communities = $('#mylist').find('.name');
var temp_exp = new RegExp("^("+match_string+")","i");
communities.each(function(i){
var current = $(this);
var name = current.text();
name = name.replace(temp_exp, '<b>$1</b>');
current.html(name);
});
while all items have to have the class "name".

Categories

Resources