How can I get the HTML of an element - javascript

For example I have:
<div id="f" style="width:50px; height:50px; background-color:#ddd">
<p>Some text</p>
</div>
I want to get <div id="f" style="width:50px; height:50px; background-color:#ddd">
This is what I have tried so far:
alert(document.getElementById("f").innerHTML);
alert(document.getElementById("f").outerHTML);
and jsfiddle of it.

There is no direct way to do this. However, you could remove the innerHTML content from the outerHTML content.
document.getElementById("f").outerHTML.replace(document.getElementById("f").innerHTML,'')

The closest I can think of is to clone it, remove all contents, get outerHTML, and then remove the </div> from the end.
var clone = document.getElementById("f").cloneNode(true);
clone.innerHTML = "";
var html = clone.outerHTML.replace(/<\/div>\s*$/, '');

You almost have the solution, using outerHTML. You just want to split the returned string after the first > character, which is easy using JS .split().
For example:
var html = document.getElementById("f").outerHTML;
var part = html.split(">")[0] + ">";
So: I get the whole HTML, split it by the > character, then add the > back in (because split() removes it).
Here's an updated fiddle of it.

Related

How to use javascript to find and replace a word split in a few tags?

I want to use javascript to find and replace a word which has been split in a few tags.
For example, the html code:
<html>
<body>
<div id="page-container">
This is an apple.
<div>
<span>a</span><span>p</span><span>ple</span>.
</div>
</div>
</body>
</html>
And the it looks like below in the web browser:
This is an apple.
apple.
I use this javascript to find and replace the word "apple":
var a = document.getElementById('page-container').innerHTML;
a=a.replace(/apple/g,'pear');
document.getElementById('page-container').innerText=a;
But the result in the web browser is very bad, and all the tags could not work:
This is an pear.
<div>
<span>a</span><span>p</span><span>ple</span>.
</div>
It seems the replace function worked for the first row but cannot recognize the word split in the tags. This is an example, the whole content could be much more complex with more tags like , , not only ... Is there a way to replace only text but keep the original html tag format?
var a = document.getElementById('page-container').textContent;
a = a.replace(/apple/g, 'pear');
var a=a.split('.');
document.getElementById('page-container').innerHTML = `${a[0]}.<br/><span> ${a[1]}
<span>`;
That is because you have nested elements, so when you set innerHTML of the parent div, it treats inner div as text and print it out , try to replace this :
document.getElementById('page-container').innerText=a;
with this :
document.getElementById("page-container").firstChild.innerHTML = a;
So, you target only your first child which is parent div.
Live example:
https://jsbin.com/hujurageya/edit?html,js,output

Javascript:: textContent/innerText of firstChild

My code is pretty much explain itself of what I'm about to get :
<div id=player>
<div class="button hand">►</div>
<div class=time>00:00/02:25</div>
<div class="timeline hand"><span class="now hand"></span></div>
</div>
<script>
var myPlayer=document.getElementById('player').firstChild;
var playerStatus=(myPlayer.innerText||myPlayer.textContent);
console.log(playerStatus);
</script>
I'm expect to get the ascii value ► on console.
Small tweak needed here
Try this:
var myPlayer=document.getElementById('player').firstElementChild;
The problem is that the first child of #player is a text node itself. What you're looking for is the first element child of #player.
A minor note: firstElementChild isn't supported by IE8-.
You have both id and class available, so use querySelector().
var myPlayer=document.querySelector('#player > .button.hand');
This also has the benefit of working in IE8.
Also, a shortcut for innerText/textContent is to check for it at the top of your script, and store the appropriate key in a string.
var text = ("textContent" in document) ? "textContent" : "innerText";
Then use square brackets with the text variable.
var myPlayer=document.querySelector('#player > .button.hand');
var playerStatus=(myPlayer[text]);
Then you can actually shorten it like this:
var playerStatus=document.querySelector('#player > .button.hand')[text];

Remove div and its content from html string

Lets say i have a string like this:
<div id="div1"></div>
<div class="aClass" id="div2">
<div id="div3" class="anotherClass"></div>
<div id="div4" />
</div>
<div id="div5"></div>
I want to remove div2 from the string and everything inside that div
So i got a string like this
<div id="div1"></div>
<div id="div5"></div>
I thinking something like using regex to find the first div with the id of "div2" or whatever the id of the div is and count brackets untill it gets to "< /div>". The problem is that the "div3" also got a "< /div>" at the end.
The content of the div i want to remove may contain more or less div's then this too.
Any ideas on how to code this?
Update:
var htmlText = editor3.getValue();
var jHtmlObject = jQuery(htmlText);
jHtmlObject.find("#div2").remove();
var newHtml = jHtmlObject.html();
console.log(newHtml);
Why doesn't this return anything in the console?
Update2!:
I have made a jsFiddle to make my problem visual..
http://jsfiddle.net/WGXHS/
Just put the string into jQuery and use find and then remove.
var htmlString = '<div id="div1"></div>\
<div class="aClass" id="div2">\
<div id="div3" class="anotherClass"></div>\
<div id="div4" />\
</div>\
<div id="div5"></div>';
var jHtmlObject = jQuery(htmlString);
var editor = jQuery("<p>").append(jHtmlObject);
editor.find("#div2").remove();
var newHtml = editor.html();
If you have access to jQuery and your HTML is part of the DOM you can use $.remove()
EG. $('#div2').remove();
If it's not part of the DOM, and you have it in a string, you can do something like:
$('#div2', $(myHTML)).remove();
jQuery .remove() will do
$("#div2").remove();
The regex option would work if you control generating the string so you can ensure things like order of the attributes and indentation. If not your best bet is to use an HTML parser. If you are working inside of a browser jQuery is a good option. If you are working server-side you'll need to find a parser for the language you chose.

Retrieve text from an element and insert it somewhere else

I'd like to get the text from between the "p" tags and put it in an other element, like this:
before:
<div id="Text">
<p>$1,200.00</p>
</div>
<div id="putText">
<p></p>
</div>
after:
<div id="Text">
<p>$1,200.00</p>
</div>
<div id="putText">
<p>$1,200.00</p>
</div>
Anyone know of a Javascript that can do this?
The below function copies the contents of the first paragraph under an element with ID ID to a paragraph under another element with ID putID.
function copyContents(id) {
var source = document.getElementById(id).getElementsByTagName("p")[0];
var target = document.getElementById("put" + id).getElementsByTagName("p")[0];
target.innerHTML = source.innerHTML;
}
copyContents("Text");
you can use following jQuery code
$('#putText p').html($('#Text p').html());
If you have jQuery at your disposal, it's fairly easy - something like this should work:
$('#putText>p').text($('#Text>p').text())
If you don't, then you'll have to resort to some DOM manipulation - the same stuff jQuery does behind the scenes, only you need to code it up yourself.

how can content between a class put in a variable after click?

How do I retrieve the content between and including the following <div class="adding"> and store it in a variable?
<div class="adding">
<b>
<div class="column">
<div class="mediumCell">
<input type="text" name="name" placeholder="توضیح" title="نام پکیج تور خارجی">
</div>
</div>
<div class="column" style="margin: 5px 3px;">
<div class="mediumCell">
<div class="adda">
</div>
</div>
</div>
</b>
</div>
var adding = '<div class="adding"><b><div class="column"><div class="mediumCell"><input type="text" name="name" placeholder="توضیح" title="نام پکیج تور خارجی"></div></div><div class="column" style="margin: 5px 3px;"><div class="mediumCell"><div class="adda"></div></div></div></b></div>'
In each click I want to get the content just once.
Unfortunately, after two or more clicks getting content several times together (E.x: after two clicks it stores the content twice).
I tried this:
$(function () {
var i = $('.adding').size();
$('.add_input').live('click', function () {
var scntDiv = '.' + $(this)
.closest('.find_input')
.find('div')
.attr('class');
var input = $(scntDiv).html();
$(this).remove();
$(input).appendTo(scntDiv);
i++;
return false;
});
});
You can use the html() method, as others have said, but there's a catch: that method returns the inner HTML content of the element, so the markup of the outer <div> element won't be included in the result.
Since you seem to want that markup, you can work around the issue with clone(), wrap() and parent():
var adding = $("div.adding").clone().wrap("<div>").parent().html();
You can get the inner HTML using the html function:
var adding = $(".adding").html():
...which will give you the browser's version of the markup within the first matching div (the first div with the class "adding"). It's fairly simple at that point to wrap it with the markup for the div, unless there are a lot of chaotic attributes involved.
However, note that the markup you get back may not be what you expect, because your HTML is invalid. b elements cannot contain div elements (b elements may only contain phrasing content; div elements are flow content), and so the browser adjust things as it sees fit to display something reasonable. This is a Bad Thing(tm), it's much better with dynamic web apps to ensure that your HTML is valid.
Is that what you're asking for ?
var adding;
$('.adding').click(function(){
adding = $(this).html();
alert(adding);
});
var adding = $(".adding").html();
maybe?

Categories

Resources