This question already has answers here:
Wrap some specified words with span in jQuery?
(2 answers)
Closed 3 years ago.
I have an HTML article with some annotations on it, this annotation refers to some text inside the body. I want to wrap this text in a <span> tag so that I can modify it as I want.
I have a SPARQL Query that returns me some info and three important variables:
element --> the id of the container element of the text
start --> position of the first character of the annotation inside the element
end --> position of the last character of the annotation inside the element
Below there is an example that maybe will clarify.
With this element:
<p class="metadata-entry" id="element_id">
<span class="generated" id="span1">Publisher: </span>
BioMed Central
<span class="generated" id="span2"> (</span>
London
<span class="generated" id="span3">)</span>
</p>
Since I have an annotation on the word "London" when I run my query I obtain:
element = "element_id"
start = 27
end = 33
Now, after my ajax call that returns these 3 values, how can I wrap the word "London" in a span so I can set its background to a specific color?
This may be a bit dirty, but I think it should work. Since you have the element that contains "London", you can replace the HTML of that element with a modified version of what's currently in there.
You can see how to use the jquery html function here:
How to replace innerHTML of a div using jQuery?
Basically, what you'd do is use it as a getter to get the HTML out of the "element_id" element, modify it using Javascript string functions by adding span tags at the start and end indexes you have, and then using the html function to replace "element_id"'s HTML with the modified string.
I hope this works for you!
EDIT: To illustrate this better, here's essentially what you'd be doing:
var currentHTML = $(element).html();
var newHTML = currentHTML.substring(0, start) + "<span style='background-color: green;'>" + currentHTML.substring(start, end) + "</span>" + currentHTML.substring(end, currentHTML.length);
$("element_id").html(newHTML);
Related
This question already has answers here:
Get caret index in contenteditable div including tags
(2 answers)
Closed 7 years ago.
I am creating a customize editor by using contenteditable div, I need a javascript code to calculate line position of current caret position on keypress event.
Please make sure It should also work when add new line or remove a line.
This is my contenteditable div format
<div contenteditable="true" id="editor">
<b>Heading</b>
<br/>
Line 1
<br/>
Line 2
<br/>
Line 3
<br/>
Line 4
<br/>
Line 5
</div>
Please see this fiddle:
Use a <pre> instead.
Html
<pre contenteditable="true" id="editor">
line 1
line 2
line 3
line 4
line 5</pre>
<input id="addBtn" type="button" value="Add Line"/>
JavaScript
$('#editor').on("mouseup", function getPos() {
var sel = document.getSelection(),
nd = sel.anchorNode,
text = nd.textContent.slice(0, sel.focusOffset);
var lineNum=text.split("\n").length;
alert(lineNum);
});
$('#addBtn').click(function(){
var str = "new line";
elem = document.getElementById("editor");
elem.innerHTML = elem.innerHTML +"\n" + str;
});
I've updated my jsfiddle, and used a pre instead <br/> (for line breaks)
Fiddle
I'm not really sure what you are trying to do but I have an idea. I had a similar project where I had to take text from input boxes. I would say get an id for each paragraph or line or input box . Then add an event to the div. Once you add the event to the div, you can pretty much do anything.
Example:
It don't have to be body, add it to your div.
document.body.addEventListener("foo_event", get_target, false);
<p id="someid">Some cool stuff here or input or whatever.
Put ids on all your lines so we can have a way to id them. Put
classes also if you want to style them</p>
function get_target(e){
//Some event happend let's do something
if ("someid" === e.target.id ) {
//Lets run some code on the paragraph or element
/*Ideally you would want an algorithm for testing ids instead of using a bunch of If statements */
}
}
Hi I am using the following code :
breakContent = breakContent.replace(/<div>/g, ' <div>');
Here breakContent is a string that contains html code. I need to provide space before div tag.The above code works fine for div without any attribute like id, style,etc...
So what I need is the working code including attributes in div tag...
I tried the below code..but it does not give space before div and instead it replace the div with space
breakContent = breakContent.replace(/<div\s*[\/]?>/gi, " ");
Just change it to:
breakContent = breakContent.replace(/<div/g, ' <div');
Removing the trailing > will allow for <div> tags with attributes.
EDIT: Of course, this could pick up text that isn't actually a <div> tag, if you have text matching <div that isn't a tag.
I am trying to change color of a part of strings. I have a list of DOM elements, and for each of them, the text can contain some hashtags. I would like to put in color all hashtags words which could be found in the text.
Here is the begin of the code :
var listOfText = document.getElementsByClassName("titleTweet");
for (var nodetext in listOfText) {
var divContent = listOfText[nodetext].innerHTML;
if (divContent.indexOf("#") !== -1) {
// Do job here
}
}
For example, divContent can be equals to "Hello my #friends ! How are you ?"
I would like to update the dom elements to put in red color the word "#friends".
I don't know how to do that using javascript or jQuery.
You can use a regexp to find the hastags and wrap them with html. Then use the .html() method to replace the original element's html with the new string.
Example snippet
$('#myDiv').replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
Working example - http://jsfiddle.net/4p4mA/1/
Edited the example to work on all divs on the page.
Note: This will only work so long as your element only contains text, because it is replacing all the child nodes with its text value.
use regex for this, find text having hashtag and replave that in span tag for each element.
$('.titleTweet').each(function(){
var $this=$(this);
$this.html($this.text()
.replace(/#[a-z0-1A-Z]+/g, '<span style="color: red;">$&</span>'));
});
See demo here
.innerHTML is a poor basis to starting replacing text. You'll want to navigate down to the text nodes and use .nodeValue to get the text. Then you can start splitting up the text nodes.
I am trying to set the value of a input button to a string variable.i.e"A Guide to the School Bus"; But when the HTML loads up only the first word comes up in the button. My code is given below. Thanks for the help.
var title="A Guide to the School Bus";
var htmlString= "<div class="+title+ ">"+"<input type="+"button "+"value="+title+" onclick=loadBook()>"+"</div>";
$(htmlString).appendTo(attachPoint);
And the attachpoint is a reference in the HTML that i got using the following.
var attachpoint=document.querySelector('.buttonAttachPoint');
The problem is because you're not putting quotes around the attribute values. Try this:
var htmlString= '<div class="'+title+'"><input type="button" value="'+title+'" onclick="loadBook()"></div>';
You can either escape all the " in your string or, like I have done, just switch between ' and ". " will show up as a normal character and ' is used to mark the start and finish of strings.
As a side point you probably wouldn't want to put the variable title as the class on the div as it would add each separate word as a class, so in your example the div would have 6 classes added to it.
I am grabbing a div from the document with :
var myTotal = window.document.getElementById('status').innerHTML;
which returns a big mess of HTML
<div id="foo">
<a href="bar" onclick='_gaq.push(["_trackEvent", "The", "Total",])'>
<img src="foo.gif" alt="foo" height="22px;/" width="15px;"></a>
</div>
<a href="bar" onclick='_gaq.push(["_trackEvent", "The", "Total",])'>
MY TOTAL:
<span style="font-size: 12px; color: #F3A428; font-weight:normal;"> 8 item(s) </span>
</a>
Can one of you expression wizards please show me how I can grab just the number in the span, in this example an 8 ?
Can you give the span an id and reference it directly?
If not, then this regex should return the number in the span: /<span[^>]+>\s*(\d+)/
I'm assuming that there is only ever one span in the div.
This should help you
var myTotal = window.document.getElementById('status').getElementsByTagName('span')[0].innerHTML
myTotal = myTotal.replace(/(^\d+)(.+$)/i,'$1');
In jQuery, without even getting the inner HTML it would be this:
var items = $("#status span").first().text();
items = parseInt(items, 10);
alert(items); // 8
If you control the HTML, it would be advisable to put a unique ID on the span containing the result and then it's easier to retrieve and not dependent upon the structure around it or better yet, have it output into the page as a JS variable that you can just directly read and not have to deal with the presentation.
Seen in a jsFiddle here: http://jsfiddle.net/jfriend00/UqcxS/
You can also try, just using innerText
window.document.getElementById('status').innerText.replace(/[^0-9]/gi, '');
http://jsfiddle.net/X9ffE/
Use jQuery instead, it has a lot of functions that can help you find specific elements in your page. Also, you may want to add identification for your elements like class and id.