Hello I would like to add HTML on to a page once it finds particular text. I have managed to get the position I just can figure out how to add text
$(document).ready(function () {
var position = document.documentElement.innerHTML.indexOf('Gas');
//insert HTML at position
})
So since you already know where to insert, just do
var str = element.innerHtml;
element.innerHTML = str.substr(0, position - 1) + "<b>My HTML</b>" + str.substr(position);
Other way it would be to wrap that text in some element and do .insertBefore()
$(document).ready(function () {
var text = $('.my-text').html();
$('.my-text').html(text.replace(/Gas/, '<span id="my-unique-id">Gas</span>'));
var htmlToInsert = $('<b>', {text: 'Inserted text'});
htmlToInsert.insertBefore('#my-unique-id');
$('#my-unique-id').unwrap();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my-text">
Abc def Gas Mesa Bas Ras
</div>
Related
My goal is to have a highlighter made in JavaScript which change some word's color multiple times.
<div id="code" contenteditable="true">
hello world hello world
</div>
I want to have an outuput as : " Hello world Hello world "
How can I change the color of both "hello" using JavaScript?
By this following code, you can write a function to find the words and replace them with a colorful element (e.g or & ...)
$(function(){
// inquire element for run the function
var elem = $('#code');
// call highlighter method with the word and elemnet
highlighter('hello', elem);
});
function highlighter(word, elem){
// get inner html from passed element
var html = elem.html();
// define a new regex for replacing the word on specified element
var reg = new RegExp(word,"g");
// replace all found words with a new wrapped word
html = html.replace(reg, "<span class='highlight'>" + word +"</span>");
// set the specified element with new html
elem.html(html);
}
.highlight {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="code" contenteditable="true">
hello world hello world
</div>
You have to split your text to get each individual word, and then add each one in different 'span' tags which will have a 'fontWeight' property set to 'bold' if the word is 'hello'.
Here's an example:
var div = document.getElementById("code");
var text = div.innerText;
div.innerText = '';
text.split(' ').forEach(x => {
const span = document.createElement('span');
span.innerText = x + ' ';
if(x == 'hello')
span.style.fontWeight = 'bold';
div.appendChild(span);
})
Try out this fiddle
I have a variable that contains HTML.
var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>'+
'<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>'+
'<p>Testing</p>';
I am trying to loop around all of the elements and replace with spans specific date. So any spans with a class of variable-source will need to be replaced with specific date, and the same for input-source.
I have tried to use the following:
$('span', html).replaceWith(function () {
var id = $(this).attr('id');
// this returns the correct id
//calculations go here
var value = 'testing';
return value
});
Which outputs the following:
testing This is a variable
All of the paragraph tags have been removed, and it seems to stop after the first paragraph. Is there something that I am missing here? I can post more code or explain more if needed.
Thanks in advance.
You need to create a html object reference, else you won't get a reference to the updated content. Then get the update content from the created jQuery object after doing the replace operations
var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>' +
'<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>' +
'<p>Testing</p>';
var $html = $('<div></div>', {
html: html
});
$html.find('span.variable-source').replaceWith(function() {
var id = this.id;
// this returns the correct id
//calculations go here
var value = 'replaced variable for: ' + id;
return value
});
$html.find('span.input-source').replaceWith(function() {
var id = this.id;
// this returns the correct id
//calculations go here
var value = 'replaced input for: ' + id;
return value
});
var result = $html.html();
$('#result').text(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>
I want to insert </div><div id = '2'> to my html page
This is current code:
<body>
<div id='1'>
<p>abc1</p>
<p>abc2</p>
</div>
</body>
This is code I want to be after insert:
<body>
<div id='1'>
<p>abc1</p>
</div>
<div id='2'>
<p>abc2</p>
</div>
</body>
My javascript code is
var bodyTag = document.getElementsByTagName("body")[0];
var divTag = bodyTag.getElementsByTagName("div")[0];
var pCount = divTag.getElementsByTagName("p").length;
var str = '</div><div id = "2">';
var insert_pos = 1;
for(var i = 0 ; i < pCount; i++)
{
if(i != insert_pos)
{
s += '<p>'+ divTag .getElementsByTagName("p")[i].innerHTML + '</p>';
}
else
{
s += '<p>'+ divTag .getElementsByTagName("p")[i].innerHTML + '</p>';
s += str;
}
}
I used javascript to insert with method innerHTML but it inserts only <div id = '2'>, </div> is not inserted.
Please help me! Thank you very much!
Try this : You can make use of .after() and .append() as shown below
$(function(){
//add div2 after div1
$('#1').after('<div id="2"></div>');
//append last p to div2
$('#2').append($('#1 p:last'));
});
JSFiddle Demo
var bodyTag = document.getElementsByTagName("body")[0];
var divTag = bodyTag.getElementsByTagName("div")[0];
var pCount = divTag.getElementsByTagName("p").length;
var str = '<div>';
var insert_pos = 1;
for(var i = 0 ; i < pCount; i++)
{
if(i == insert_pos)
{
str += '<p>'+ divTag .getElementsByTagName("p")[i].innerHTML + '</p>';
}
}
str+='</div>';
bodyTag.innerHTML+=str;
<body>
<div id='1'>
<p>abc1</p>
<p>abc2</p>
</div>
</body>
I think this could fulfill.
var pEls = document.getElementsByTagName('p'),
parentDivEl = document.getElementById('1'),
targetPEl = parentDivEl.removeChild(pEls[1]);
var divEl = document.createElement('div');
divEl.id = "2";
divEl.appendChild(targetPEl);
parentDivEl.parentNode.insertBefore(divEl, parentDivEl.nextSibling);
<body>
<div id='1'>
<p>abc1</p>
<p>abc2</p>
</div>
</body>
Using Javascript, here you go...
var pEls = document.getElementsByTagName('p'),
parentDivEl = document.getElementById('1'),
targetPEl = parentDivEl.removeChild(pEls[1]);
var divEl = document.createElement('div');
divEl.id = "2";
divEl.appendChild(targetPEl);
parentDivEl.parentNode.insertBefore(divEl, parentDivEl.nextSibling);
This one is interesting. I originally tried to use the insertAdjacentHTML function to insert the string '</div><div id="2">' after the first <p>, but strangely, the Dom rearranges these divs automatically to be '<div id="2"></div>'.
So, the next best option is to just do it manually. I'm not sure if this will work in your case, but it does output the desired result with less javascript.
Check out this fiddle.
http://jsfiddle.net/justinbchristensen/k2y2uggj/
var div1 = document.getElementById('1');
var ps = div1.children;
div1.removeChild(ps[1]);
div1.insertAdjacentHTML('afterend','<div id="2"><p>abc2</p></div>');
1) Get the div by its ID, assign it to a variable 'div1'
2) Access the 2 child <p> of the div and assign them to 'ps'
3) Remove the second <p>
4) Insert the entire second <div> with its child <p>
Let me know if this will work for your situation. If not, I'm sure we can come up with something more creative.
Thank you very much. I want to save the process time so I find the way to insert code like that. But it seems no way to insert. So, the right way to do is Moving the childs in this div to another. Thanks for your solution :)
I'm trying to create a simple page that "corrects" YouTube's old embed code so that it works in PowerPoint 2010. If I hard code the embed code into a textarea on the page, it works fine, but if the user pastes the embed code into the text area, the javaScript doesn't seem to run.
Take a look here:http://jsfiddle.net/pch8N/
Here's what I have so far:
<p>Click the button to "fix" the old embed code</p>
<textarea rows="10" cols="60" id="demo"></textarea>
<br/>
<script>
function myFunction()
{
var str=document.getElementById("demo").innerHTML;
var n=str.replace(/\/\/www.youtube/g,"http://www.youtube").replace(/version=3/g,"version=2");
document.getElementById("demo").innerHTML=n;
}
</script>
<button onclick="myFunction()">Try it</button>
Thanks for the help!
You should use value instead of innerHtml
function myFunction2()
{
var str=document.getElementById("demo2").value;
var n=str.replace(/\/\/www.youtube/g,"http://www.youtube").replace(/version=3/g,"version=2");
document.getElementById("demo2").value=n;
}
var str=document.getElementById("demo").innerHTML;
You should use .value and not .innerHTML
Put your textarea inside form tag
Then use
var str=document.getElementById("demo").value;
// hope this would be usefull
// i used these codes for auto completing the texts in textarea.
// other methods change all matching items before the selected text
// but this affects only the text where caret on.
// at first, i divided textarea.value into 3 pieces. these are ;
// p1; until the 'searched' item, p2 after 'searched' item
// and pa = new item that will replaced with 'searched' item
// then, i combined them together again.
var tea = document.getElementById(targetTextArea);
caretPosition = tea.selectionStart - ara.length; //ara=searched item
p1 = tea.value.substring(0,caretPosition);
console.log('p1 text : ' + p1);
p2 = tea.value.substring(caretPosition+ara.length,tea.value.length);
console.log('p2 text : ' + p2);
pa = yeni; //new item
console.log('pa text : ' + pa);
tea.value = p1 + pa + p2;
tea.selectionStart = caretPosition + yeni.length;
tea.selectionEnd = caretPosition + yeni.length;
tea.focus();
I want add new input text before paragraph. But it working opposite add after text.
What is wrong at this code?
I use document.getElementById("p1").insertBefore(node); with this aim, but without success. Why does this happen?
Code:
<html>
<head>
<title>Adding text to a page</title>
<script>
function addText() {
var sentence=document.form1.sentence.value;
var node=document.createTextNode(sentence + " ");
document.getElementById("p1").insertBefore(node);
}
</script>
</head>
<body>
<h1>Create Your Own Content</h1>
<p id="p1">Using the W3C DOM, you can dynamically
add sentences to this paragraph. Type a sentence
and click the Add button.</p>
<form name="form1">
<input type="text" name="sentence" size="65">
<input type="button" value="Add" onClick="addText();">
</form>
</body>
</html>
Question:
How to solve this issue?
The insertBefore method needs to be called on the parent node (in which you want to insert), just like appendChild:
var node=document.createTextNode(sentence + " ");
var p1 = document.getElementById("p1");
p1.parentNode.insertBefore(node, p1);
If you want to add sentences to the paragraph instead of before it (right into the <body>), you would use this:
p1.appendChild(node); // insert at the end
// or
p1.insertBefore(node, p1.firstChild); // insert at the beginning
You could
Grab the new sentence.
Grab the original content.
Put them both together in a variable.
Clear the element.
Slap it back in.
Like so:
var addText = function() {
var sentence = document.form1.sentence.value;
var node = document.createTextNode(sentence + " ");
var el = document.getElementById("p1");
var original = el.innerHTML;
var newPara = sentence + ". " + original;
el.innerHTML = "";
el.innerHTML = newPara;
}
jsFiddle
Mind you, this is alot of steps, but hey, a million ways to skin a cat.
Of course you could always shorten all of that code up there to this:
var addText = function() {
document.getElementById("p1").innerHTML = document.form1.sentence.value + ". " + document.getElementById("p1").innerHTML;
}
new jsFiddle