access DOM and change element font and colour - javascript

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

Related

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

Jquery select object by id dynamically using a string

I have an image gallery that uses modals. In the image modal or outside it, the user can click on a star and mark the image as favorite. Favorite images have a class that makes the star change color its to 'golden'. If a user marks a favorite in the modal, I need to change the color of the star of that image outside the modal as well.
To do this, I thought I could have a
<p id = "modal_counter" class = "hidden">number</p>
in the modal, so that I can get the image number. Then I use that image number as part of a jquery selector.
The images in the gallery have something like this:
<p id = "image_number" class = "hidden"></p>
<!-- for example: <p id = "image_2" class = "hidden"></p> -->
So, all I need is to successfully select the hidden p tag next to each image, then I could use jquery's next() or parent().find().
This is the relevant code:
...
var modal_counter = div_parent.find('#modal_counter').text();
var counter = "#image_"+String(modal_counter);
/* I would like the counter to be something like "#image_2" */
var $(counter).parent().find('.star').addClass('golden')
...
This doesn't work. Jquery tries to find an object using this selector:
"#image_\n 2"
and of course, it doesn't find one. I tried removing the \n with a regex, but it still doesn't work:
counter_processed = modal_counter.replace(/(<([^>]+)>)/ig,"");
It'll probably be better to use a data-attribute on your element rather than getting the text content. Do:
<p id = "modal_counter" class = "hidden" data-counter="number">number</p>
Then you can:
...
var modal_counter = div_parent.find('#modal_counter').data('counter');
var counter = "#image_" + modal_counter;
/* I would like the counter to be something like "#image_2" */
var $(counter).parent().find('.star').addClass('golden')
...
This way you don't bind your javascript to the text inside your elements.
jQuery has a handy trim function:
var modal_counter = div_parent.find('#modal_counter').text().trim();
Try this from your console:
$.trim("\n\nHello\r\nThere\n")
See how it removes the leading and trailing white-space?
Let's say you have:
<p id="modal_1" class="hidden">Img 1</p>
you can extract the number both using:
// If you need it from the text
var n = $("[id^=modal_]").text().match(/\d+/); // 1
or
// If you need it from the ID
var n = $("[id^=modal_]")[0].id.match(/\d+/); // 1
Than to target the image like:
<img id="image_1" src="someimage.jpg" alt="SEO">
you do:
$('#image_'+ n)
If you really just have:
<p id="modal_counter" class="hidden">3</p>
than you can do:
var n = $('#modal_counter').text(); // "3"
$("#image_"+ n) // .fadeIn() or whatever...
Just make sure you don't have duplicate modal_counter ID elements on your page. ID has to be unique.

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

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())

Javascript Gets the contents of the textarea of the distance from the border pixels

How can I be sure the text in the input box, the number of pixels from the left box? It may have utf8, Chinese
This might not be the best way, but i guess this can be a start. This will return the number of pixels remaining in the input element:
function getRemainingWidth(element){
var span = $('<span class=\"'+$(element).attr('class')+'\" style=\"visibility:hidden;\">'+$(element).val()+'</span>');
$(document.body).append(span);
var diff = $(element).width() - $(span).width();
$(span).remove();
return diff;
}
One way to do it is creating a span element and adding your text to it. But there is a catch: you have to add it to the dom in order get its with:
var sYourText = 'asdfafdsa, dzcvxvxc';
var oText = document.createElement('span');
oText.innerHTML = sYourText;
document.getElementsByTagName('body')[0].appendChild(oText)
console.log(oText.offsetWidth);
Of course: be sure to apply the same font that your textarea have.
$("textarea").keyup(function(){
var s = $(this).val()
var data = s.replace(/(\s)/g,' ')
console.log(data)
$('span').html(data)
})
I replace it with a regular spaces replaced, but wrapping problems that may require using CSS

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');
})

Categories

Resources