I am new to javascript. I was thinking getelementbyid but i don't know how to make it work
Like the title, here is what I mean
For example I have in HTML:
<p>fw_93</p>
<p>fw_94</p>
<p>fw_93</p>
So what I want is to make script to replace those fw_93 fw_94 to what I want.
For example
Instead of displaying "fw_93" I want it to display "9.3". Same with fw_94 to 9.4
Replace fw_ with nothing, divide the number by 10:
Array.prototype.forEach.call(document.getElementsByTagName('p'), function(el) {
el.innerHTML = parseInt(el.innerHTML.replace(/[A-Za-z_]*/, '')) / 10;
});
<p>fw_93</p>
<p>fw_94</p>
<p>fw_93</p>
Okay so select the tags.
Loop over the collection
read the html
match the string
replace the html
var ps = document.querySelectorAll("p");
for (var i=0; i<ps.length; i++) {
var p = ps[i];
var txt = p.innerHTML; //.textContent
var updated = txt.replace(/.+(\d)(\d)/, "$1.$2");
p.innerHTML = updated;
}
<p>fw_93</p>
<p>fw_94</p>
<p>fw_93</p>
Using JQuery
Not sure why I did it with JQuery, guess I wasn't paying enough attention. No point in me re-writing as there are already good answers in JS. Though I will leave this in case it's of use to anyone that is using JQuery.
You can loop though each <p> element and covert the contents, something like this:
$("p").each(function() {
var text = $(this).html();
var text = text.substring(text.indexOf("_") + 1);
var text = text[0] + "." + text.substring(1);
$(this).html(text);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>fw_93</p>
<p>fw_94</p>
<p>fw_93</p>
You may need to add validation depending on how reliable your input is.
Note that the code makes the following assumptions:
There will always be a _ followed by at least 2 digits
The . will always go after the first digit
Your HTML:
<p id="p1">init_value</p>
Your JS:
document.getElementById("p1").innerHTML = "new_value";
Related
My goal is to take an array, and write each element onto a HTML page using a <span> element with .textContent using a for loop. Only problem is that instead of:
Error1
Error2
I get:
Error1<br/>Error2<br/>
HTML code:
<p><span id="EBox"></span></p>
JS code:
var EBox = document.getElementById("EBox");
var eArray = []; //Elements get added via push
for (var i = 0; i < eArray.length; i++) {
EBox.textContent = EBox.textContent + eArray[i] + '<br/>';
}
The entire system works, but it just ends up as one jumbled sentence. What can I change to make it add the line breaks? I've tried '<br>', '<br />' and '\n' with similar results.
Use .innerHTML .insertAdjacentHTML instead of .textContent as .textContent does not parse the HTML <br> but simply outputs it as text.
Also if you're appending to the HTML each time, it's better to use .insertAdjacentHTML as it does not reparse the previous HTML, thus making it much faster and less error prone than .innerHTML.
var strArr = ['foo', 'bar'];
strArr.forEach(function(str) {
document.querySelector('div').insertAdjacentHTML('beforeend', str + '<br>');
});
<div></div>
Instead of .textContent use .innerHTML.
I would also recommend building up a string first before using .innerHTML so the DOM isn't rebuilt each time...
var EBox = document.getElementById("EBox");
var eArray = []; //Elements get added via push
var html = "";
for (var i = 0; i < eArray.length; i++) {
html += eArray[i] + '<br/>';
}
EBox.innerHTML = html;
I found a better answer here:
https://developer.mozilla.org/pt-BR/docs/Web/CSS/word-break
You can use CSS to do this, see below:
span{word-break: break-word;}
or
span{word-break: break-all;}
BREAKE-WORD will put the next word in a new line and BREAKE-ALL will break the text justifying the content, when it gets bigger than the div or span container.
I hope I'd help :)
I got like;
<p>Variable Text</p>
And I want to it to be;
<p>Variable <span>Text</span></p>
Is this possible by a javascript function? / or jQuery.
Oh yeah, and the p-element got an ID and the text inside the p-element is variable but always consists of 2 words. I want a span around the last word of the text by a javascript function.
Try this
var txt = "Hello bye";
var dataArr = txt.split(' ');
var paragraph = document.getElementById("pid");
paragraph.innerHTML = dataArr[0]+ " <span>"+dataArr[1]+"</span>";
Here is a demo
It's possible (the following assumes the p has an ID, like you said), in it's simplest form you can just do:
var paragraph = document.getElementById("pId");
paragraph.innerHTML = "Hello <span>World</span>";
Or if you want to use jQuery:
$("#pId").html("Hello <span>World</span>");
Or (as you said in comments, you want to keep the existing content, but wrap the last word in a span, you can do:
var newHTML = $("#pId").html().replace(" ", " <span>");
$("#pId").html(newHTML).append("</span>");
DEMO
I would like to share a jQuery solution, which is regardless of any words defined in your p element
$("p").html(function(){
var mystring= $(this).text().split(" ");
var lastword = mystring.pop();
return mystring.join(" ")+ (mystring.length > 0 ? " <span>"+ lastword + "</span>" : lastword);
});
Demo
In the demo above, I am splitting the string first, than am using pop to get the last index in the array, and than am adding span element and returning the string using join
$("document").ready(function(){
$("p").append("<span>world</span>");
});
With JQuery append
$("#paragraphId").append('<span>Text in span</span>');
jQuery is easier, and personally I think it's better to use than only javascript:
jQuery:
$("#paragraphID").append("<span>World</span>");
HTML:
<p id="paragraphID">Hello</p>
I have this HTML code:
<div>
756
<span></span>
</div>
Using JavaScript I want to retrieve the number 756 from within the div tag and increment it by 1. What is the best method of filtering out the <span> from within the div tags so I get only the number?
Try this:
var div = document.getElementsByTagName("div")[0],
content = div.textContent || div.innerText;
textContent is supported by all browsers except IE8- and innerText is supported in all browsers except FF4-. So using both, you should get a stable result.
http://www.quirksmode.org/dom/w3c_html.html
Both properties return the text content with stripped HTML tags.
Example: http://jsfiddle.net/HnWxk/ (tested in chrome/ff/ie7)
Now, if you want to increment it, just do:
content++;
It should cast a Number: http://jsfiddle.net/HnWxk/3/
You can use .innerText to do so.
var div = document.getElementsByTagName("div")[0];
var inner;
if(div.innerText) {
inner = div.innerText;
} else {
inner = div.textContent;
}
var number = parseInt(inner);
number++;
alert(number);
Fiddle.
<div id="mydiv">
756
<span></span>
</div>
<script>
var textNode = document.getElementById("mydiv").childNodes[0];
var number = parseInt(textNode.nodeValue);
textNode.nodeValue= number + 1;
</script>
DEMO
Just an other way to do it without the browser incompatibility of innerText and textContent. I use innerHTML after I use a regular expression to extract the number, Also it is recommended to always define the radix when you use parseInt (will simply avoid some weird surprise I let you discover) and finally incrementing the value.
var theNum = parseInt(document.getElementById('someDiv').innerHTML.match(/\d+/), 10);
alert(theNum+=1)
The best solution would be to wrap the number in its own <span>.
If that is not possible (you don't create the HTML code), you can iterate over all child nodes of the <div>. One of them will be the text node you want to target.
<div id="number">
756
<span></span>
</div>
d = document.getElementById("number")
n = parseInt(d.innerHTML)+1;
alert(n);
Assuming this html code:
<div id="someDiv">
756
<span></span>
</div>
You can use this (with jquery):
var div = $("#someDiv");
div.text(parseInt(div.text()) + 1);
I used split on the text to get the number.
Also used jQuery to get the text, you can use the other methods people used here.
var divText = $('div').text();
var contentArray = divText.split('\n');
var yay = parseInt(contentArray[1].trim(), 10);
alert(yay);
alert(yay++);
See fiddle here.
The best way would be wrap the number in an element, but you can workaround with this:
var div = document.getElementById('div')
var num = parseInt((div.innerText) ? div.innerText : div.textContent);
div.childNodes[0].nodeValue = num + 1;
Is it possible to match "the dog is really really fat" in "The <strong>dog</strong> is really <em>really</em> fat!" and add "<span class="highlight">WHAT WAS MATCHED</span>" around it?
I don't mean this specifically, but generally be able to search text ignoring HTML, keeping it in the end result, and just add the span above around it all?
EDIT:
Considering the HTML tag overlapping problem, would it be possible to match a phrase and just add the span around each of the matched words? The problem here is that I don't want the word "dog" matched when it's not in the searched context, in this case, "the dog is really really fat."
Update:
Here is a working fiddle that does what you want. However, you will need to update the htmlTagRegEx to handle matching on any HTML tag, as this just performs a simple match and will not handle all the cases.
http://jsfiddle.net/briguy37/JyL4J/
Also, below is the code. Basically, it takes out the html elements one by one, then does a replace in the text to add the highlight span around the matched selection, and then pushes back in the html elements one by one. It's ugly, but it's the easiest way I could think of to get it to work...
function highlightInElement(elementId, text){
var elementHtml = document.getElementById(elementId).innerHTML;
var tags = [];
var tagLocations= [];
var htmlTagRegEx = /<{1}\/{0,1}\w+>{1}/;
//Strip the tags from the elementHtml and keep track of them
var htmlTag;
while(htmlTag = elementHtml.match(htmlTagRegEx)){
tagLocations[tagLocations.length] = elementHtml.search(htmlTagRegEx);
tags[tags.length] = htmlTag;
elementHtml = elementHtml.replace(htmlTag, '');
}
//Search for the text in the stripped html
var textLocation = elementHtml.search(text);
if(textLocation){
//Add the highlight
var highlightHTMLStart = '<span class="highlight">';
var highlightHTMLEnd = '</span>';
elementHtml = elementHtml.replace(text, highlightHTMLStart + text + highlightHTMLEnd);
//plug back in the HTML tags
var textEndLocation = textLocation + text.length;
for(i=tagLocations.length-1; i>=0; i--){
var location = tagLocations[i];
if(location > textEndLocation){
location += highlightHTMLStart.length + highlightHTMLEnd.length;
} else if(location > textLocation){
location += highlightHTMLStart.length;
}
elementHtml = elementHtml.substring(0,location) + tags[i] + elementHtml.substring(location);
}
}
//Update the innerHTML of the element
document.getElementById(elementId).innerHTML = elementHtml;
}
Naah... just use the good old RegExp ;)
var htmlString = "The <strong>dog</strong> is really <em>really</em> fat!";
var regexp = /<\/?\w+((\s+\w+(\s*=\s*(?:\".*?"|'.*?'|[^'\">\s]+))?)+\s*|\s*)\/?>/gi;
var result = '<span class="highlight">' + htmlString.replace(regexp, '') + '</span>';
A simpler way with JQuery would be.
originalHtml = $("#div").html();
newHtml = originalHtml.replace(new RegExp(keyword + "(?![^<>]*>)", "g"), function(e){
return "<span class='highlight'>" + e + "</span>";
});
$("#div").html(newHtml);
This works just fine for me.
Here is a working regex example to exclude matches inside html tags as well as javascripts:
http://refiddle.com/lwy6
Use this regex in a replace() script.
/(a)(?!([^<])*?>)(?!<script[^>]*?>)(?![^<]*?<\/script>|$)/gi
this.keywords.forEach(keyword => {
el.innerHTML = el.innerHTML.replace(
RegExp(keyword + '(?![^<>]*>)', 'ig'),
matched => `<span class=highlight>${matched}</span>`
)
})
You can use string replace with this expression </?\w*> and you'll get your string
If you use jQuery, you can use the text property on the element containing the text you're searching for. Given this markup:
<p id="the-text">
The <strong>dog</strong> is really <em>really</em> fat!
</p>
This would yield "The dog is really really fat!":
$('#the-text').text();
You could do your regex search on that text instead of trying to do so in the markup.
Without jQuery, I'm unsure of an easy way to extract and concatenate the text nodes from all child elements.
I was wondering if it is possible to use JavaScript to add a <div> tag around a word in an HTML page.
I have a JS search that searches a set of HTML files and returns a list of files that contain the keyword. I'd like to be able to dynamically add a <div class="highlight"> around the keyword so it stands out.
If an alternate search is performed, the original <div>'s will need to be removed and new ones added. Does anyone know if this is even possible?
Any tips or suggestions would be really appreciated.
Cheers,
Laurie.
In general you will need to parse the html code in order to ensure that you are only highlighting keywords and not invisible text or code (such as alt text attributes for images or actual markup). If you do as Jesse Hallett suggested:
$('body').html($('body').html().replace(/(pretzel)/gi, '<b>$1</b>'));
You will run into problems with certain keywords and documents. For example:
<html>
<head><title>A history of tables and tableware</title></head>
<body>
<p>The table has a fantastic history. Consider the following:</p>
<table><tr><td>Year</td><td>Number of tables made</td></tr>
<tr><td>1999</td><td>12</td></tr>
<tr><td>2009</td><td>14</td></tr>
</table>
<img src="/images/a_grand_table.jpg" alt="A grand table from designer John Tableius">
</body>
</html>
This relatively simple document might be found by searching for the word "table", but if you just replace text with wrapped text you could end up with this:
<<span class="highlight">table</span>><tr><td>Year</td><td>Number of <span class="highlight">table</span>s made</td></tr>
and this:
<img src="/images/a_grand_<span class="highlight">table</span>.jpg" alt="A grand <span class="highlight">table</span> from designer John <span class="highlight">Table</span>ius">
This means you need parsed HTML. And parsing HTML is tricky. But if you can assume a certain quality control over the html documents (i.e. no open-angle-brackets without closing angle brackets, etc) then you should be able to scan the text looking for non-tag, non-attribute data that can be further-marked-up.
Here is some Javascript which can do that:
function highlight(word, text) {
var result = '';
//char currentChar;
var csc; // current search char
var wordPos = 0;
var textPos = 0;
var partialMatch = ''; // container for partial match
var inTag = false;
// iterate over the characters in the array
// if we find an HTML element, ignore the element and its attributes.
// otherwise try to match the characters to the characters in the word
// if we find a match append the highlight text, then the word, then the close-highlight
// otherwise, just append whatever we find.
for (textPos = 0; textPos < text.length; textPos++) {
csc = text.charAt(textPos);
if (csc == '<') {
inTag = true;
result += partialMatch;
partialMatch = '';
wordPos = 0;
}
if (inTag) {
result += csc ;
} else {
var currentChar = word.charAt(wordPos);
if (csc == currentChar && textPos + (word.length - wordPos) <= text.length) {
// we are matching the current word
partialMatch += csc;
wordPos++;
if (wordPos == word.length) {
// we've matched the whole word
result += '<span class="highlight">';
result += partialMatch;
result += '</span>';
wordPos = 0;
partialMatch = '';
}
} else if (wordPos > 0) {
// we thought we had a match, but we don't, so append the partial match and move on
result += partialMatch;
result += csc;
partialMatch = '';
wordPos = 0;
} else {
result += csc;
}
}
if (inTag && csc == '>') {
inTag = false;
}
}
return result;
}
Wrapping is pretty easy with jQuery:
$('span').wrap('<div class="highlight"></div>'); // wraps spans in a b tag
Then, to remove, something like this:
$('div.highlight').each(function(){ $(this).after( $(this).text() ); }).remove();
Sounds like you will have to do some string splitting, though, so wrap may not work unless you want to pre-wrap all your words with some tag (ie. span).
The DOM API does not provide a super easy way to do this. As far as I know the best solution is to read text into JavaScript, use replace to make the changes that you want, and write the entire content back. You can do this either one HTML node at a time, or modify the whole <body> at once.
Here is how that might work in jQuery:
$('body').html($('body').html().replace(/(pretzel)/gi, '<b>$1</b>'));
couldn't you just write a selector as such to wrap it all?
$("* :contains('foo')").wrap("<div class='bar'></div>");
adam wrote the code above to do the removal:
$('div.bar').each(function(){ $(this).after( $(this).text() ); }).remove();
edit: on second thought, the first statement returns an element which would wrap the element with the div tag and not the sole word. maybe a regex replace would be a better solution here.