Replace node with innerhtml - javascript

With JavaScript I want to remove a specific DOM node and replace it with the innerHTML. For example I want to change
<div>
...
<div id="t1">
this is <b> the text </b> I want to remain.
</div>
...
</div>
To
<div>
...
this is <b> the text </b> I want to remain.
...
</div>

Try this:
var oldElem = document.getElementById('t1');
oldElem.innerHTML = 'this is <b> the text </b> I want to remain.';
var parentElem = oldElem.parentNode;
var innerElem;
while (innerElem = oldElem.firstChild)
{
// insert all our children before ourselves.
parentElem.insertBefore(innerElem, oldElem);
}
parentElem.removeChild(oldElem);
There is a demo here.
This is effectively the same thing as .replaceWith() from jQuery:
$("#t1").replaceWith('this is <b> the text </b> I want to remain.');

var t1 = document.getElementById("t1");
t1.outerHTML = "this is <b> the text </b> I want to remain.";
http://youmightnotneedjquery.com/#replace_from_html

If you are using jQuery, you can try
var inner = j$("#t1").html()
$('#t1').replaceWith(inner);

This works:
var t1 = document.getElementById("t1");
t1.parentNode.innerHTML = t1.innerHTML;
Edit:
Please note that if the parent of t1 has any other children, the above will remove all those children too. The following fixes this problem:
var t1 = document.getElementById("t1");
var children = t1.childNodes;
for (var i = 0; i < children.length; i++) {
t1.parentNode.insertBefore(children[i].cloneNode(true), t1);
}
t1.parentNode.removeChild(t1);

It's very easy actually:
let span = document.getElementById('id');
span.outerHTML = span.innerHTML;

I just modified the HTML Like this.
<div>
<div id="t0">
<div id="t1">
this is <b> the text </b> I want to remain.
</div>
</div>
</div>
And you do something like
document.getElementById("t0").innerHTML = "this is <b> the text </b> I want to remain.";
Hope it works

you might want to consider using jquery if that's possible.
it would make your life way way wayyyyyyyy easier.
once you have jquery, you can easily do this via
$("#t1").html("this is <b> the text </b> I want to remain.");
and if you find it a hassle to learn, you can always start by learning the jquery selectors.
you wouldn't know why you haven't been using it all this while :)
sorry if this is not what you want exactly..
~jquery addict
Updated:
To show what html text to put inside.

This is similar to the other answers but more functional.
go.onclick = () => {
[...t1.childNodes].forEach(e => {
t1.parentElement.insertBefore(e, t1);
});
t1.remove();
go.disabled = true;
}
#t1 {
color: red;
}
<div>
<div>BEFORE</div>
<div id="t1">
this is <b> the text </b> I want to remain.
</div>
<div>AFTER</div>
<button id="go">GO</button>
</div>

Related

Converting some text within an element to an element itself using JavaScript

Is this possible using JavaScript or JQuery, or anything else?
Say I have an HTML file like this
<div>
<p>Hello World</p>
</div>
And I want to turn "World" into a span element itself, like so (so that I can style just "World")
<div>
<p>Hello <span>World</span></p>
</div>
Since there are a lot of unknowns in your question, so I am assuming that you already know the string/word around which you want to add the html tag.
So keeping that in mind, following solution should work:
HTML:
<div>
<p id="my-text">Hello World, Again!</p>
</div>
JavaScript:
const stringToBeReplaced = "World"; // what you want to replace
const innerText = document.getElementById("my-text").innerText; //grab the text
const beginIndex = innerText.indexOf(stringToBeReplaced); // get text where string begins
// if string exists
if (beginIndex >= 0) {
const textWithTag =
"<span style='color: red'>" + stringToBeReplaced + "</span>";
const newString = innerText.replace(stringToBeReplaced, textWithTag);
// replace the text with new string
document.getElementById("my-text").innerHTML = newString;
}
Hope this is what you were asking and looking for.
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_replace3
str.replace solves the job. The comment of #Umer Hassan is correct.

how to post HTML code without the browser rendering

I'm to build a forum for the project, but right now I'm facing this problem where I want users to be able to post their HTML source code as it works in this forum.
But the problem is that the code runs or scatters my design when retrieve from my DB.
I tried using repalce() in jQuery but I could only replace < with < but I want a function to be able to replace others such as >,",' and & so my question is how can I update this function.
function convert(div){
var str = $(div).html();
var str2 = str.replace(/</g,"<");
var sta = $(div).html(str2);
return sta;
}
The above code work to replace the < but when I try including >,",' and & in the function it will stop work how can i make it work.
Thanks in advance.
Stick it in <pre> or <code> tags, or both, and make sure you use text() when inserting the content to the tag
function convert(div){
var str = $(div).html();
var sta = $('<code />', {text : str});
return sta;
}
var result = convert( $('#test') );
$('#result').html(result)
#result {
white-space : pre;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
<span>
<p>TEST</p>
</span>
</div>
<br />
<div id="result">
<code> will preserve the code, and <pre> will preserve whitespace, but there's also the CSS white-space property, that can act as a <pre> tag using the pre setting

How can I dynamically wrap elements in a div within another div?

I have the following output of WordPress content:
link1
text1
<br>
<br>
link2
text2
<br>
<br>
link3
text
<br>
<br>
link4
text4
<br>
<br>
I DO NOT have access to edit the content so I'm looking to edit this via jQuery. I need to wrap each link with the text and br before next link in a div and then split it in two columns. So the final result would be something like this:
<div class="col-left">
<div class="item">
link1
text1
<br>
<br>
</div>
<div class="item">
link2
text2
<br>
<br>
</div>
</div>
<div class="col-right">
<div class="item">
link3
text3
<br>
<br>
</div>
<div class="item">
link4
text4
<br>
<br>
</div>
</div>
Any idea how can I achieve this using jQuery?
I have tried using .wrap() like this:
$('a').wrap( "<div class='item'></div>" );
That's a pretty fun challenge.
A quick explanation...
jQuery appears to struggle when getting text elements which aren't wrapped in any tag, so we must fist wrap them. I've used a <span>. I've used the code from this post to do that.
Now that they're all wrapped up nicely, we can select the elements we're interested in, and find the halfway point. If we have an odd number, let's call Math.ceil, so that the extra one ends up in the Left column.
var a = $('a');
var i = Math.ceil(a.length/2);
Now let's just get the first column and second column elements by calling $.slice.
var firstColEls = a.slice(0,i);
var secondColEls = a.slice(i);
We can now loop through the elements and add the <div> with the item class. I'm using itemC1 and itemC2 so we can quickly select all the grouped elements later on. The class can have the same styling.
$.each(firstColEls, function(idx,el){
$(el).nextUntil('a').addBack().wrapAll('<div class="itemC1"></div>');
});
$.each(secondColEls, function(idx,el){
$(el).nextUntil('a').addBack().wrapAll('<div class="itemC2"></div>');
});
Now let's select the items, and wrap all of them (together) in the left/right column divs!
$('.itemC1').wrapAll('<div class="l"></div>');
$('.itemC2').wrapAll('<div class="r"></div>';
Wasn't that fun? :). Working Fiddle.
Have you tried setting a variable like so:
if (check how many links) {
var wrapLinkLeft = $('<div class="col-left"><div class="item">link1<br><br></div></div>');
var wrapLinkRight = $('<div class="col-right"><div class="item">link2<br><br></div></div>');
$(wrapLinkLeft).appendTo('body'); //for example append it to the body
}
to make the link dynamic leave it empty and just append it to the href, which means you will probably need to set a class or ID for this href or build a counter to keep track of where the scripts at.
This is the closest I could get. It gives the desired outcome, but I'm not sure that it's terribly flexible.
var textNodes = $('a').first().parent().contents().filter(function() {
return this.nodeType === 3 && $(this).text() !== "\n";
});
$(textNodes).each(function() {
$(this).wrap('<span></span>');
});
var groups = $('a');
$(groups).each(function(index, item) {
$(item).before('<div class="item"></div>');
var theDiv = $(item).prev();
var theItem = $(item).detach();
var theRest = theDiv.nextUntil('a').detach();
theDiv.append(theItem);
theDiv.append(theRest);
theDiv.find('span').contents().unwrap();
});
var theDivs = $('.item');
var half = theDivs.length / 2;
$(theDivs).first().before('<div class="col-left"></div><div class="col-right"></div>');
var i;
for (i = 0; i < half; i++)
{
var nextDiv = $(theDivs[i]).detach();
$('.col-left').append(nextDiv);
}
for (; i < theDivs.length; i++)
{
var nextDiv = $(theDivs[i]).detach();
$('.col-right').append(nextDiv);
}
And here's the JSFiddle. Cheers.

javascript with jQuery - how to change specific Text

How can i change followed given HTML code via javascript and jQuery:
<div> <strong> unimportant text here </strong> important text here </div>
Goal is to change the Text in the <div> .... important text here </div> without touching the ...
<strong> unimportant text here </strong>
...part
Example:
*unimportant text here * important and changed text here
jsFiddle Demo
This requires having access to the parent div. I am not sure how you would like to access it, but for example, I will use an id.
<div id="d"> <strong> unimportant text here </strong> important text here </div>
This allows for the inner element to targeted. You should just use substring in order to select the latter part of the text
var AllText = $('#d').text();
var StrongElementText = $('#d strong').text();
var ImportantText = AllText.substr(StrongElementText.length);
Edit
With no way to target the element directly, it will have to be inferred (which can lead to target collision)
jsFiddle Demo Using Inferred target
$('div strong').each(function(){
var AllText = this.parentNode.innerText;
this.parentNode.innerText += " And Changed";
var StrongElementText = this.innerText;
var ImportantText = AllText.substr(StrongElementText.length);
c[0].innerHTML += ImportantText + "<br>";//shows output
});
<div>
<strong> unimportant text here </strong>
<span id="changeText">important text here</span>
</div>
$('#changeText').text= "I CHANGE THE TEXT";

jQuery find and replace string

I have somewhere on website a specific text, let's say "lollypops", and I want to replace all the occurrences of this string with "marshmellows". The problem is that I don't know where exactly the text is. I know I could do something like:
$(body).html($(body).html().replace('lollypops', 'marshmellows'));
This would probably work, but I need to rewrite as little HTML as I can, so I'm thinking something like:
search for the string
find the closest parent element
rewrite only the closest parent element
replace this even in attributes, but not all, for example replace it in class, but not in src
In example, I would have structure like this
<body>
<div>
<div>
<p>
<h1>
<a>lollypops</a>
</h1>
</p>
<span>lollypops</span>
</div>
</div>
<p>
<span class="lollypops">Hello, World!</span>
<img src="/lollypops.jpg" alt="Cool image" />
</p>
<body>
In this example, every occurrence of "lollypops" would be replaced, only <img src="... would remain the same and the only elements that would actually be manipulated would be <a> and both <span>s.
Does anybody know how to do this?
You could do something like this:
$("span, p").each(function() {
var text = $(this).text();
text = text.replace("lollypops", "marshmellows");
$(this).text(text);
});
It will be better to mark all tags with text that needs to be examined with a suitable class name.
Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.
You could do something this way:
$(document.body).find('*').each(function() {
if($(this).hasClass('lollypops')){ //class replacing..many ways to do this :)
$(this).removeClass('lollypops');
$(this).addClass('marshmellows');
}
var tmp = $(this).children().remove(); //removing and saving children to a tmp obj
var text = $(this).text(); //getting just current node text
text = text.replace(/lollypops/g, "marshmellows"); //replacing every lollypops occurence with marshmellows
$(this).text(text); //setting text
$(this).append(tmp); //re-append 'foundlings'
});
example: http://jsfiddle.net/steweb/MhQZD/
You could do something like this:
HTML
<div class="element">
<span>Hi, I am Murtaza</span>
</div>
jQuery
$(".element span").text(function(index, text) {
return text.replace('am', 'am not');
});
Below is the code I used to replace some text, with colored text. It's simple, took the text and replace it within an HTML tag. It works for each words in that class tags.
$('.hightlight').each(function(){
//highlight_words('going', this);
var high = 'going';
high = high.replace(/\W/g, '');
var str = high.split(" ");
var text = $(this).text();
text = text.replace(str, "<span style='color: blue'>"+str+"</span>");
$(this).html(text);
});
var string ='my string'
var new_string = string.replace('string','new string');
alert(string);
alert(new_string);
Why you just don't add a class to the string container and then replace the inner text ? Just like in this example.
HTML:
<div>
<div>
<p>
<h1>
<a class="swapText">lollipops</a>
</h1>
</p>
<span class="swapText">lollipops</span>
</div>
</div>
<p>
<span class="lollipops">Hello, World!</span>
<img src="/lollipops.jpg" alt="Cool image" />
</p>
jQuery:
$(document).ready(function() {
$('.swapText').text("marshmallows");
});

Categories

Resources